#9 – Main() Should Not Be Public
June 26, 2010 4 Comments
The following code will compile, but is not recommended, according to the MSDN documentation. If Main() is public, other classes could call it. But this violates the intent for Main(), which is meant to only be called once, when the program is invoked.
class Program { static public void Main() { Console.WriteLine("This would compile.."); } }
When i am executing this program , i am getting error “the name console does not exist in current context.
Sounds like you’re missing a using on the namespace System. Did you create your app using the wizard in Visual Studio, so that all of the basic stuff gets created? Note that this post presents a code fragment–not a complete program.
public class Program
{
static public void Main()
{
Console.Write(“Hello World”);
}
}
public class A
{
public void HelloWorld()
{
Program obj = new Program();
obj. ——— Main function can’t be able to access here
}
I made main function as public and tried to access in other classes, but can’t be able to access it.
Main() is a static function, so you can’t access it through an object variable.