Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 505
jai Avatar asked Feb 19 '14 04:02

jai


People also ask

What is the difference between public static void and private static void?

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.

What is the difference between public static void main and static void Main?

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.

What is the difference between public and private static void in Java?

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.

What is private static void Main?

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.


2 Answers

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.

like image 98
Ergwun Avatar answered Oct 06 '22 14:10

Ergwun


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.

public

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.

private

like image 44
Zaheer Ahmed Avatar answered Oct 06 '22 14:10

Zaheer Ahmed