What is the difference between
public static void Main()
and
private static void Main()
in a C# console appli
There is difference, because first one is public and second one is private, so when you'd try to use the first one from outside the class it would work just fine, but wouldn't work with the second one.
However, there is no difference if you're trying to make one of these an entry point in you application. Entry point method can be either public or private, it doesn't matter.
The private or public statement is it's access modifier, a private access modifier makes it inaccessible to external objects where a public access modifier makes it accessible to external objects. example usage:
Say we have a class:
class myClass{
public void test(){
//do something
}
}
We create an instance of that class:
myClass mClass=new myClass();
To access it's member function you would go:
mClass.test();
If it had a private access modifier, you'd get a compile error saying it's inaccessible.
And just for knowledge's sake, to access a member without creating an instance of a class, you'd also make that member static, eg:
class myClass{
public static void test(){
//do something
}
}
So to access it now, you'd just simply do:
myClass.test();
(Note that any members accessed in a static member should also be static)
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.
The main is marked as the entry point for execution in the exe itself when it is private so anything from outside cannot access it
Making it public will make the method accessible from outside
Read for more clarification http://social.msdn.microsoft.com/Forums/vstudio/en-US/9184c55b-4629-4fbf-ad77-2e96eadc4d62/why-is-main-in-c-not-a-public-static-?forum=csharpgeneral
For most purposes it will make no difference. Microsoft advocates making Main private.
The only real value in doing this (as far as I am aware) is that it will prevent the Main method from being invoked directly by another application's codebase.
A good discussion of it is available here
public and private are the access specifiers.
we use,
public static void Main()
because to execute the program, you need to call your class in which this Main() method is present, for that you need your Main() method to be public otherwise it will not be accessible outside the class.
And the reason why it is static is, because, it needs to be accessed without creating any objects of that class .i.e. at class level.