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
Is an Int a 64-Bit Integer in 64-Bit C#
How to Access Page Controls Inside a Static Web Method
Invalidprogramexception/Common Language Runtime Detected an Invalid Program
Why Aren't Generic Type Constraints Inheritable/Hierarchically Enforced
Wpf Clickonce Dpi Awareness Per-Monitor V2
Remove Item in Dictionary Based on Value
Regular Expression to Get the Src of Images in C#
Newtonsoft JSON Deserialize Dictionary as Key/Value List from Datacontractjsonserializer
Moq + Unit Testing - System.Reflection.Targetparametercountexception: Parameter Count Mismatch
How to Log All Thrown Exceptions
Dynamically Create a Generic Type for Template
Unable to Load Cvextern in a C# Project
C# Httpwebrequest the Underlying Connection Was Closed: an Unexpected Error Occurred on a Send