Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should the Main() method be static?

Tags:

c#

I tried to create public void Main() in C#; it says no static void Main found.
What exactly does it mean for Main to be static? I know the code works fine for public static void Main().

But why does Main have to be static?

like image 387
Indish Avatar asked Jul 04 '12 16:07

Indish


4 Answers

You need an entry point into your program. Static means that you can call the function without having to instantiate an object/instance of a class. It's a bit "chicken and egg"... you can't instantiate an object before you're inside the program.

A static method can be called without instantiating an object. Therefore main() needs to be static in order to allow it to be the entry to your program.

As David says, you can just add the keyword static to the function definition to change it. It's worth looking into static (class) methods vs instance methods, and knowing the difference can be useful at times.

like image 98
Thomas Clayson Avatar answered Oct 19 '22 17:10

Thomas Clayson


Only the static main method can do the job because there is a convention that defines this behavior. There is not another reason.

Take a look at the C# language specification:

Application startup occurs when the execution environment calls a designated method, which is referred to as the application's entry point. This entry point method is always named Main, and shall have one of the following signatures:

     static void Main() {…}  
     static void Main(string[] args) {…}  
     static int Main() {…}  
     static int Main(string[] args) {…}

As shown, the entry point can optionally return an int value. This return value is used in application termination (§10.2).

Note: The above is quoted from the 4th edition, now labeled "historical". The current edition is worded differently.

In addition to that, the name Main can be changed to something else. In this case a compiler option must be added telling the C# compiler to mark a different method as the entry point of the program.

like image 25
Leonardo Cruz Avatar answered Oct 19 '22 15:10

Leonardo Cruz


There are two types of method within a class:

  1. Non-static method
  2. Static method

// Example of static and non-static methods and how to call
namespace TestStaticVoidMain
{
    class Program
    {
        Static Void Main(string[] args)
        {
           // Instantiate or create object of the non-static method:
            Exam ob = new Exam();
            // Call the instance:
            ob.Test1();

            // Directly the call the static method by its class:
            Exam.Test2();

            Console.ReadKey();
        }
    }
    class Exam
    {
        public void Test1()
        {
            Console.WriteLine("This is a non-static method");
        }

        public static void Test2()
        {
            Console.WriteLine("This is a static method");
        }
    }
}

1. Static method:

To call a static method (function), we don't need to instantiate or create an object of that method. We can't use new keyword because, when the class is loaded and compiled, the static keyword by default instantiates or creates an object of that class method, so that is why we directly call a static method.

In reference to static void Main(string[] args), we already discussed static. The remainder is void Main(string[] args). void is a data type which returns nothing. Main() is the standard entry point to execution of a C# program. The optional argument string[] args receives the optional "command line" parameters that the program was run with.

2. Non-static sethod:

To call a non-static method, we have to instantiate or create an object of the class method to call the method (function) of the class using the keyword new.

If a class named Test has a non-static method named show(), then how it would call an instance:

// to call non-static method
Test ob=new Test();
ob.show();
like image 37
raga Avatar answered Oct 19 '22 15:10

raga


Conceptually, it would be possible for a framework to specify that rather than using a particular static method to run a program, it will instead construct a default instance of some particular class and run some particular method thereon. If one had a framework which implemented static methods by having them be instance members of a compiler-initialized singleton instance, such an approach might be entirely reasonable, since the framework would have to generate a new object instance before calling the main function in any case.

If calling a static method is "easier" than constructing a new object instance and calling a method thereon, however, there isn't really much benefit to requiring that a framework use the more expensive course of action. Any code which wants to use the latter approach would be perfectly free to use:

public static void Main( [[params]] )
{
  var mainObject = new MainObject();
  mainObject.Main( [[params]] );
}

There could be some potential benefits to having the system include its own static method which looked something like:

public static void SysMain( [[params]] )
{
  using (Application app = new UserApp( [[params]] )) // UserApp derives from Application
  {
    app.Start(); // Virtual method
    app.AllowNext(); // Base method--see text
    app.Run(); // Abstract method
  }
}

where app.AllowNext() was a method to coordinate with other application instances launched at essentially the same time, to ensure that repeated attempts to launch an application in background would have their Start calls processed strictly sequentially. Absent such a coordination scheme, however, there's not really much benefit to requiring that the framework construct an application object before running it. The cost wouldn't be huge, but without any potential identifiable benefit there's not much point in accepting even a trivial cost.

like image 29
supercat Avatar answered Oct 19 '22 15:10

supercat