why main() contains static?
why main() contains static?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jignesh TrivediPosted Sep 23, 2013, 1:18 AM
hi,
Main() function is entry point of program / application so I think, static functions exist before a class is instantiated that is why static is applied to the main entry point
Please refer
http://www.codeproject.com/Articles/479467/Main-Method-in-Csharp
http://msdn.microsoft.com/en-us/library/ms228506(v=vs.90).aspx
hope this will help you.
Sanjeeb LenkaPosted Sep 23, 2013, 12:20 AM
Static methods are the methods which do not require any object whenever they are called. These methods are loaded even before the class is loaded in the memory. It means that even before the object is being created . the method is already loaded into the memory. Other than this, Main() is the entry point for any program. It means whenever you run a program, the compiler looks out for the Main method. If there is a main method then the content onside it is executed.... The main method is the first access point for any program and has to be called automatically. Since it is static it gets loaded automatically even before the object of that class is being created and. Main() does not require any object to be called!
class MyClass
{
public void myDetails()
{ Console.WriteLine("Hello World"); }
public static void Main()
{
MyClass m = new MyClass();
m.myDetails();
}
}
See in this example, i have created a non-static method which requires an object to be called. The method gets loaded into the memory when the complier
executes the line m.myDetails(); Main method is static and does not requires an object to be created to call it.Hence it is static and the other reason is that it is the entry point for any program.
VulpesPosted Sep 22, 2013, 6:05 AM
class Program
{
void Main(string[] args)
{
// code
}
}
The CLR would then need to create an object of type Program before it could call the Main() method.
So the Main() method would not be the entry-point to the program - it would be Program's constructor instead.
The Main() method therefore needs to be static to avoid this situation.