Sobes.tech
Junior — Middle

Kuidas eristada staatilist meetodit meetodist, mis kutsutakse konkreetse klassi objektil?

sobes.tech AI

Vastus AI-lt

In C#, a static method is defined with the keyword static and is called on the class itself, not on an instance of an object.

Differences:

  • Static method:

    • Declared with static.
    • Does not have access to non-static fields and methods of the class.
    • Called via the class name: ClassName.Method().
  • Instance method:

    • Does not contain static.
    • Called on a specific object: obj.Method().

Example:

class MyClass
{
    public static void StaticMethod()
    {
        Console.WriteLine("Static method");
    }

    public void InstanceMethod()
    {
        Console.WriteLine("Instance method");
    }
}

// Calls
MyClass.StaticMethod(); // call static method

MyClass obj = new MyClass();
obj.InstanceMethod(); // call on object

The main difference is in the way of calling and the presence of the static keyword.