Why is Main method private?

11,357

Solution 1

The entry point of a program is marked with the .entrypoint IL directive. It does not matter if the method or the class is public or not, all that matters is this directive.

Solution 2

The Main method shouldn't need to be called by anyone.

It is actually marked as the entry point for execution in the EXE itself, and therefore has no outside callers by default.

If you WANT, you can open it up to be called by marking public, e.g. if you are turning a console app into an API.

Solution 3

Yes. You can mark the main() method as public, private or protected. If you want to initiate the entry point by any external program then you might need to make it public so it is accessible. You can mark it as private if you know there is no external usage for the application then it is better to make it private so no external application access it.

public class MainMethod
{
    private  static void Main(string[] args)
    {
        Console.WriteLine("Hello World !!");
    }
}
Share:
11,357
František Žiačik
Author by

František Žiačik

Updated on June 11, 2022

Comments

  • František Žiačik
    František Žiačik almost 2 years

    New console project template creates a Main method like this:

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

    Why is it that neither the Main method nor the Program class need to be public?

  • Michael Stum
    Michael Stum almost 14 years
    That also means you don't even have to call the main method "Main". The C# Compiler enforces that, but other .net languages can use whatever they want.
  • Anders Abel
    Anders Abel almost 13 years
    Even if the functionality of the console program should be callable directly by other assemblies, it is often a bad idea to open up Main. It is better design to expose a public Facade that external programs can call. Main handles command line arguments and then calls into the same Facade.
  • dhara tcrails
    dhara tcrails almost 13 years
    @Anders: Fair point, but we are just talking about feasibility, not design.
  • mins
    mins almost 5 years
    This should be the selected answer.