58

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?

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Indish
  • 739
  • 1
  • 7
  • 12
  • A similar question was asked about java and I think the answers apply here too: http://stackoverflow.com/questions/146576/why-is-the-java-main-method-static – Tudor Jul 04 '12 at 16:13
  • 6
    It's not clear whether you're asking because you don't understand what `static` means *in general* or whether this is specifically around `Main`. – Jon Skeet Jul 04 '12 at 16:14

6 Answers6

67

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.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Thomas Clayson
  • 29,657
  • 26
  • 147
  • 224
  • 37
    “you can't instantiate an object before you're inside the program.” That’s patently false. The runtime instantiates lots of objects before `Main` is executed. You can trigger that yourself by putting a static constructor into the class containing `Main`. Sorry, I realise this thread is > 1 year old but I feel that this is relevant. – Konrad Rudolph Sep 01 '13 at 12:56
  • 9
    The key point is: the language is defined not to instantiate an object, then call Main on it. It is defined to call a static function. It could work differently, but doesn't. – usr Sep 01 '13 at 13:10
19

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.

Leonardo Cruz
  • 1,189
  • 9
  • 16
  • 9
    YOUR ANSWER explains very well what is a static method. You also explained that the main method is the entry point of the program. But the questioner already knew that. What he wants to know is why he must use a static method. MY ANSWER says that there is no fundamental cosmic reason. The language designers chose this way. Probably it is an influence of other languages like C, C + + and Java. – Leonardo Cruz Jul 05 '12 at 20:00
  • 2
    I see you did not understand what I said! It's about a design decision. Forget it – Leonardo Cruz Jul 06 '12 at 18:15
  • 4
    @ThomasClayson language designers could have well decided to create an instance of Program and call Main on it. I think both answers are correct, it is a design decision because they took into consideration what you said in your answer, IMHO – BlackBear Sep 01 '13 at 12:53
  • 5
    This is the (only!) correct answer. The others are quite wrong, for reasons highlighted [in a more detailed discussion on Programmers.SE](http://programmers.stackexchange.com/q/156336/2366) /cc @ThomasClayson. – Konrad Rudolph Sep 01 '13 at 12:59
5

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();
A876
  • 471
  • 5
  • 8
raga
  • 59
  • 1
  • 2
1

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.

supercat
  • 77,689
  • 9
  • 166
  • 211
0

During app startup, when no objects of the class have been created, the Main method must be called to begin program execution. Main is sometimes called the app’s entry point. Declaring Main as static allows the execution environment to invoke Main without creating an instance of the class. Method Main is typically declared with the header:

static void Main(){..}

but also can be declared with the header:

static void Main(string[] args){..}

You can declare Main with return type int (instead of void)—this can be useful if an app is executed by another app and needs to return an indication of success or failure to that other app.

Neri Barakat
  • 1,555
  • 20
  • 25
-1

The main should be static that it loads first and become your entry point to your program so it's crucial for the main to be static.