66

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?

John Gietzen
  • 48,783
  • 32
  • 145
  • 190
František Žiačik
  • 7,511
  • 1
  • 34
  • 59

4 Answers4

60

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.

dtb
  • 213,145
  • 36
  • 401
  • 431
  • 18
    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. – Michael Stum Jun 25 '10 at 21:16
30

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.

John Gietzen
  • 48,783
  • 32
  • 145
  • 190
  • 3
    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. – Anders Abel Jul 21 '11 at 19:22
  • 2
    @Anders: Fair point, but we are just talking about feasibility, not design. – John Gietzen Jul 21 '11 at 21:25
  • This should be the selected answer. – mins Jul 06 '19 at 06:05
2

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 !!");
    }
}
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
Vinayak Savale
  • 538
  • 6
  • 7
  • By default class members are private, so no need to put the "private" access modifier in this case. – MadJoRR Aug 19 '23 at 12:56
0

Public or Private keyword doesn't make a difference in this case, it completely depends on usage and scope of the application. Use below mentioned keywords in different scenarios.

  1. Public - If we want to initiate entry point by any external program, then you might need to make it public so it is accessible.
  2. Private - If we know there is no external usage for the application, then it is better to make it private so no external application access it.
Pang
  • 9,564
  • 146
  • 81
  • 122