#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..");
    }
}
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: