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

回眸只為那壹抹淺笑 提交于 2019-12-04 22:13:32

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.

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?

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.

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

How could you create your class instance before main otherwise?

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!