Why Is Main Method Private

Why is Main method private?

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.

Can the main( ) method be specified as private or protected?

It will compile, it will not run (tested using Eclipse).

Why does my program work if my Main method in C# is private?


Thats not true.

It has to be public. For e.g. public static void Main().

EDIT: Here is what I found & learned today, on why Main need not be public.
http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/9184c55b-4629-4fbf-ad77-2e96eadc4d62/

Why can I access a private variable from main method?

Main is a part of you class, you have declared it inside your class :)
What main is not is part of your object, it will not be any part of the objects you create from the class but it is still part of the class. This is correct for any static function as main is just a normal static function that the framework knows it should look for when the program is executed.

Why a class containg a main method doesn't need to be public in Java?

Just for kicks, a demo that private classes can also hold main:

class Outer {
private static class Inner {
public static void main(String[] args) {
System.out.println("Hello from Inner!");
}
}
}

Compiles and runs fine from the command line:

C:\junk>javac Outer.java

C:\junk>java Outer$Inner

Hello from Inner!

C:\junk>

Why main method is marked as public?

The initialization software that starts your program must be able to see main so that it can call it.

What is the difference between public static void Main() and private static void Main() in a C# console application?

To act as the start point in your application, the Main method is not required to be public.

If you did decide to make it public, it would be possible for it to be called from other classes or assemblies. Typically you will not need to do this, so you can keep it private.

One possible use case for making it public would be to allow automated tests to invoke it.



Related Topics



Leave a reply



Submit