#9 – Main() Should Not Be Public

The following code will compile, but is not recommended, according to the MSDN documentation. If Main() is public, other classes could call it.  But this violates the intent for Main(), which is meant to only be called once, when the program is invoked.

class Program
{
    static public void Main()
    {
        Console.WriteLine("This would compile..");
    }
}

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #9 – Main() Should Not Be Public

  1. Anup Baghel says:

    When i am executing this program , i am getting error “the name console does not exist in current context.

    • Sean says:

      Sounds like you’re missing a using on the namespace System. Did you create your app using the wizard in Visual Studio, so that all of the basic stuff gets created? Note that this post presents a code fragment–not a complete program.

  2. Vasanth says:

    public class Program
    {
    static public void Main()
    {
    Console.Write(“Hello World”);
    }
    }
    public class A
    {
    public void HelloWorld()
    {
    Program obj = new Program();
    obj. ——— Main function can’t be able to access here

    }

    I made main function as public and tried to access in other classes, but can’t be able to access it.

Leave a comment