What is the difference between
public static void Main()
and
private static void Main()
in a C# console application? Specifically as it pertains to the Main()
method (I understand the differences between public
and private
).
public means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details. static means that the method is associated with the class, not a specific instance (object) of that class.
public − This is the access specifier that states that the method can be accesses publically. static − Here, the object is not required to access static members. void − This states that the method doesn't return any value.
public static - can be accessed from within the class as well as outside the class. private static - can be access from within the class only.
Explanation: 1)public: It is an access specifier which allows the JVM(Java Virtual Machine) to access the main method from anywhere. 2)static: static keyword allows the JVM to access the main method without any instance(object). 3)void: It specifies that the main method doesn't return anything.
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.
The difference between both is the only difference in public
and private
access modifiers because both are valid.It totally depends on the usage of application which one to use.
If you want to initiate entry point by any external program, (ie use as API, for testing purpose) then you might need to make it public so it is accessible.
If you know there is no external usage for the application then it is better to make it private so no external application get access to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With