call a static method on an instance of a class in csharp

To call a static method on an instance of a class in C#, you can simply use the class name followed by the method name. Static methods belong to the class and not to the instance of the class, so they can be accessed without instantiating the class. Here's an example:

main.cs
public class MyClass
{
    public static void MyStaticMethod()
    {
        // Code here
    }

    public void MyInstanceMethod()
    {
        // Code here
    }
}

// Call static method on class:
MyClass.MyStaticMethod();

// Call instance method on instance of class:
var myObject = new MyClass();
myObject.MyInstanceMethod();

// Call static method on instance of class:
myObject.MyStaticMethod(); // This is not allowed and will result in a compile error.
463 chars
23 lines

In the last line of the example above, calling a static method on an instance of a class is not allowed and will result in a compile error. This is because static members are not associated with instances of a class, but rather with the class itself.

gistlibby LogSnag