Why main is static in C# ? [Resolved]

Posted by Akiii under C# on 9/22/2011 | Points: 10 | Views : 12824 | Status : [Member] | Replies : 3
Hi folks,

Can anyone please tell me with an example, why main is static in C# ?

Thanks and Regards
Akiii




Responses

Posted by: Shiv007 on: 9/23/2011 [Member] Starter | Points: 50

Up
0
Down

Resolved
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 door 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..... Neways this much is what i have got to tell you!!!

Hope this much information is OK... If get confused then please post your query..

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rickeybglr on: 9/23/2011 [Member] Starter | Points: 25

Up
0
Down
http://msdn.microsoft.com/en-us/library/79b3xss3.aspx

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Akiii on: 9/24/2011 [Member] Bronze | Points: 25

Up
0
Down
@rickey....
thanks for the link..

@Shivanand...
its a nice explanation.......thanks for your answer...
But please do post your code in code tags, it will look elegant....

Regards
Akiii

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response