Search code examples
c#methodsstatic

What's a "static method" in C#?


What does it mean when you add the static keyword to a method?

public static void doSomething(){
   //Well, do something!
}

Can you add the static keyword to class? What would it mean then?


Solution

  • A static function, unlike a regular (instance) function, is not associated with an instance of the class.

    A static class is a class which can only contain static members, and therefore cannot be instantiated.

    For example:

    class SomeClass {
        public int InstanceMethod() { return 1; }
        public static int StaticMethod() { return 42; }
    }
    

    In order to call InstanceMethod, you need an instance of the class:

    SomeClass instance = new SomeClass();
    instance.InstanceMethod();   //Fine
    instance.StaticMethod();     //Won't compile
    
    SomeClass.InstanceMethod();  //Won't compile
    SomeClass.StaticMethod();    //Fine