Programming Blog

Simple but potentially useful – A collection of random programming stuffs

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.