Why Is Main Static?
Posted by letmetutoryou on January 27, 2009
Making Main static allows it to be invoked without the runtime needing to create an instance of the class. Non-static methods can only be called on an object, as shown in the following code:
class Example
{
void NonStatic( ) { … }
static void Main( )
{
Example eg = new Example( );
eg.NonStatic( ); // Compiles
NonStatic( ); // compile-time error
}
…
}
This means that if Main is non-static, as in the following code, the runtime needs to create an object in order to call Main.
class Example
{
void Main( )
{
…
}
}
In other words, the runtime would effectively need to execute the following code:
Example run = new Example( );
run.Main( );
Advertisement