Learn About Main() Method In C#

Main() method is the starting point of an application. When we run a program, this is the first method which gets called.

We have a lot of different flavors of this method.

Overloading of Main() Method

We can overload the Main(), however, to run the C# code, it should have a signature like “Public static void main(string[] args)”. If we don’t have this, the compiler will throw an exception.

Example: 

In the below example, we can see the main method is overloaded and we are still able to run the program.

Code Snippet

  1. using System;  
  2. namespace ConsoleApplication  
  3. {  
  4.     class Program  
  5.     {  
  6.         public class MainMethod  
  7.         {  
  8.             public static void Main(string[] args)  
  9.             {  
  10.                 Console.WriteLine("Hello World!!!");  
  11.                 Console.ReadLine();  
  12.             }  
  13.             void Main(int args)  
  14.             {  
  15.                 Console.WriteLine("First overloaded main method is called !!!");  
  16.             }  
  17.             string Main(int ID, string Name)  
  18.             {  
  19.                 Console.WriteLine("Second overloaded main method is called !!!");  
  20.                 return Name;  
  21.             }  
  22.         }  
  23.     }  
  24. }  

Change return type of Main() method

We can even change the return type of Main() from void to any other type. We can see in the below example, I have used return type as integer and the build was successful.

Code Snippet

  1. using System;  
  2. namespace ConsoleApplication  
  3. {  
  4.     class Program  
  5.     {  
  6.         public class MainMethod  
  7.         {  
  8.             public static int Main(string[] args)  
  9.             {  
  10.                 return 1;  
  11.             }  
  12.         }  
  13.     }  
  14. }  

Main() method as private

We can also make the Main() method as private and compile successfully without fail. And not only private, we can use Protected also. The difference between public and private access modifiers is that, if we want to call the main from external, then we use the public method while if we are aware that there is no external usage of the application, we use private.

Code Snippet

  1. using System;  
  2. namespace ConsoleApplication  
  3. {  
  4.     class Program  
  5.     {  
  6.         public class MainMethod  
  7.         {  
  8.             private static int Main(string[] args)  
  9.             {  
  10.                 return 1;  
  11.             }  
  12.         }  
  13.     }  
  14. }  
Next Recommended Reading Main Method In C#