Tony The Lion
Tony The Lion

Reputation: 63250

Why is the main method entry point in most C# programs static?

Why is the main method entry point in most C# programs static?

Upvotes: 39

Views: 3830

Answers (8)

mukesh
mukesh

Reputation: 1

for every objects of a class contains main method and other methods and variables , there are separate copies of each variable and methods contained by all objects but a main class copy is only one between them and so to make a copy between number of objects we have to make main method as static.

Upvotes: -3

Eric Lippert
Eric Lippert

Reputation: 660417

I'd turn the question around. What is the compelling benefit of implementing the feature that allows Main to be an instance method? Features are expensive; if there is no compelling benefit, they don't get implemented.

Do you have a really good reason why Main should be allowed to be an instance method?

Upvotes: 17

fastcodejava
fastcodejava

Reputation: 41117

Static methods can be executed without creating an instance. By convention, they have the main method as the default method to call.

Upvotes: 0

Asad
Asad

Reputation: 21928

The .NET runtime calls the Main method. (Note: Main may also be called from elsewhere, e.g. from the code Main() in another method of ExampleClass.) The static keyword makes the method accessible without an instance of ExampleClass. So Main method is an entry point and must be declared static.

Otherwise, the program would require an instance, but any instance would require a program.

To avoid that irresolvable circular dependency main is used as an entry point


reference : http://en.wikipedia.org/wiki/C_Sharp_(programming_language

Upvotes: 0

rerun
rerun

Reputation: 25505

Conceptually you only have one instance of a static. And a static method maps well to the idiom of a single staring point for a program. The language designers could have created a special program class to use with a main method but chose to create a single static function as the entry point. On some levels its really just a design choice.

Upvotes: 4

JaredPar
JaredPar

Reputation: 755259

In order to call an instance method you need an instance of an object. This means in order to start your program the CLR would need to create an instance of say Program in order to call the method Main. Hence the constructor of Program would run before Main which defeats the purpose of having a main altogether.

Upvotes: 60

Vlad
Vlad

Reputation: 35594

How could you create your class instance before main otherwise?

Upvotes: 1

David Morton
David Morton

Reputation: 16505

Because otherwise it would have to create an object, and running the constructor could cause negative side effects.

Upvotes: 1

Related Questions