Why STATIC keyword in C# main () method is Used?

Answer: The Static keyword in C# main () method is used, so that compiler can call it without or before creation of an object.

class Program
{
   		 static void Main(string[] args)
   		 {
   		 }
}

Actually,  the main () method is the default starting point of execution of a program, that compiler calls. And the compiler must hit the main () method to execute the program first.

Now, the question is, how compiler is going to call main () method that resides within a class. We know that a method in a class must be called by an object if method is not static, or, if  a method is static, then it can be called by using class name only and an object is not required.

Recommended to read static and non-static method call in C# programming.

Since, compiler has to call the main () method first, it cannot create object of the class “Program” before the main () method, as execution starts from main and before that object creation not possible. So, there is only option is to make the main () method static.

Static method call – C# program example

class A
{
    //Static method
    public static void foo()
    {
        Console.WriteLine("I'm Static method");
    }
}


class Program
{
    static void Main(string[] args)
    {
       //just by class name.
        A.foo();
        
    }
}

Related Posts