When we use top level statements in C# 9 (and later), where we can omit static void Main(string[] args)
and internal class Program
, our program does not begin at the Main
method; but rather, <Main>$
. We can verify this by adding a throw statement.
This program only has one throw statement and uses top level statements:
throw new Exception("foo bar");
When we run it, we see:
Unhandled exception. System.Exception: foo bar
at Program.<Main>$(String[] args) in C:\Users\User\source\repos\test\test\Program.cs:line 1
See how it outputs:
at Program.<Main>$
but not:
at Program.Main
Why not begin at a simple Main method and not <Main>$
when we use top level statements? Is there an actual reason for this? I'm just curious.
If you use top level statements, then the compiler will generate for you a main. So if you try to name a method Main, the compiler would be confused.
To avoid this confusion, the compiler generates the method with a special name, like <Main>$
, rather than the traditional Main. This name is unique and ensures there's no conflict with any user-defined Main methods.