Why should the Main() method be static?

C#

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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][1]:

> 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][2], 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.

[1]: https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-334.pdf "ECMA-334, current edition" [2]: http://ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-334%204th%20edition%20June%202006.pdf "ECMA-334, 4th edition (historical)"

Solution 3 - C#

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();

Solution 4 - C#

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.

Solution 5 - C#

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.

Solution 6 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIndishView Question on Stackoverflow
Solution 1 - C#Thomas ClaysonView Answer on Stackoverflow
Solution 2 - C#Leonardo CruzView Answer on Stackoverflow
Solution 3 - C#ragaView Answer on Stackoverflow
Solution 4 - C#supercatView Answer on Stackoverflow
Solution 5 - C#Neri BarakatView Answer on Stackoverflow
Solution 6 - C#Muhammad HamadaView Answer on Stackoverflow