Sobes.tech
Junior

Mis vahe on staatilise meetodi ja näidismetodi vahel?

sobes.tech AI

Vastus AI-lt

The static method belongs to the class and can be called without creating an instance of the class. It operates on the static data of the class. The instance method belongs to a specific object (instance of the class) and requires its creation to be called. It operates on the data of that specific instance.

Examples:

public static class Math  
{  
    // Static method: belongs to the Math class
    public static int Add(int a, int b)  
    {  
        return a + b;  
    }  
}  

public class MyClass  
{  
    public int InstanceData { get; set; }  

    // Instance method: belongs to the MyClass object
    public void SetInstanceData(int data)  
    {  
        InstanceData = data;  
    }  
}  

// Usage
// Calling the static method
int sum = Math.Add(2, 3);  

// Creating an instance of the class to call the instance method
MyClass obj = new MyClass();  
obj.SetInstanceData(10);