Alex Rivera | Logout

C# entry point function

Asked 2011-05-10T18:09:58.000
21

Is it necessary to use static void main() as the entry point function in C#, or can we use some other function? Why is main() static?

c#
Edit
Report

3 Answers

25

Before C# 9, the entry point had to be declared explicitly. C# 9 introduces top level statements which allow the entry point to be generated implicitly. (Only a single source file in a project can include top-level statements, however.)

When the entry point is declared explicitly, it has to be Main. It's static because otherwise the CLR would need to worry about creating an instance of the type - which means you'd presumably have to have a parameterless constructor, even if you didn't want an instance of the type, etc. Why would you want to force it to be an instance method?

Even with top-level statements, your actual program still has an entry point called Main - it just doesn't appear in your source code.

answered 2011-05-10T18:13:33.620
11

Yes, for a C# application, Main() must be the entry point.

The reason is because that's what the designers of the language decided to be what to look for as an entry point for your program. They could just as well have used a totally different approach to find the entry point, e.g. using meta data, or instantiating an object for you (which would require a parameterless constructor). Another reason for naming it void main() is that it's intuitive for users coming from other languages.

answered 2011-05-10T18:12:06.883
2

The required entry point is actually:

static void Main(string[] args); // note capitalization and arguments

The reason that Main must be static is that non-static objects must be constructed before you call any methods on them. Since Main is the entrance point of the program, who's going to call its constructor?

(Yes, you could have the CLR require that the class with Main contain a default parameterless constructor, and make the CLR call that constructor during global startup. But that's extra work, and in practice it's easier to just require that Main be static.)

answered 2011-05-10T18:14:57.247

Your Answer