Sep 20, 2011

Main method in C#

Main method in C sharp


Important points about main method in c sharp:

1. C sharp programs begins from Main method and end with any null statement.
2. A c sharp program can have only one Main method.
3. Main method must be static.

Why Main method in c# is declared as static?
Answer:
As we know Main method in c sharp is called by operating system. If Main method is static then is very easy to call the Main using the class name. For example:

class Program
    {
        static void Main(string[] args)
        {
        }
    }

Operating system will call the Main method is as: Program.Main()
Suppose Main method is not static then operating system has to call it by using object of class.  Consider a c# program without any default constructor:

class Program
    {
        //Constructor
        Program(int val)
        {
        }

        void Main(string[] args)
        {
        }
    }

We can create the object of class Program as:
Program Obj = new Program(10);

Issue 1: To create an object of class operating system to has to execute some code. As we know in C# program execution starts from Main methods. Then where this code will be executed?

Issue 2: In the above example what operating system will pass the value to the constructor? What would be the value of val? 
There as some more ambiguities if we will not declare Main method as static method. So in c# we declare Main method as static method.

4. Main method cannot public.
For native code which call the Main method has not any issue Main method is either public or private. In c sharp Main method cannot be public for encapsulation i.e. to restrict the visibility of Main method.

5. Main method can be declared inside a class or a structure. For example:
Main method inside a class:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("exacthelp.blogspot.com");
            Console.ReadKey();
        }
    }
}

Output:
exacthelp.blogspot.com

Main method inside a structure:
using System;

namespace ConsoleApplication1
{
    struct Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("exacthelp.blogspot.com");
            Console.ReadKey();
        }
    }
}

Output:
exacthelp.blogspot.com

1 comment:

  1. Awesum very clear and understandable .
    thank you very much

    ReplyDelete