Why should the Main() method be static?

后端 未结 5 565
無奈伤痛
無奈伤痛 2020-12-08 04:34

I tried to create public void Main() in C#; it says no static void Main found.
What exactly does it mean for Main to be static? I kno

5条回答
  •  星月不相逢
    2020-12-08 05:14

    You need an entry point into your program. Static means that you can call the function without having to instantiate an object/instance of a class. It's a bit "chicken and egg"... you can't instantiate an object before you're inside the program.

    A static method can be called without instantiating an object. Therefore main() needs to be static in order to allow it to be the entry to your program.

    As David says, you can just add the keyword static to the function definition to change it. It's worth looking into static (class) methods vs instance methods, and knowing the difference can be useful at times.

提交回复
热议问题