How Glass decompiles top-level statements
A modern console app has no Main you can find — the compiler hides your top-level statements in a synthesized Program class behind an unspeakable method named <Main>$, and a top-level await turns that method into an async state machine with a separate synchronous entry-point wrapper. This post reads the real metadata and IL csc emits, shows why the type keeps a speakable name while the method does not, and how Glass.NET recognises the <Main>$ fingerprint to print valid top-level-statement C# instead of an un-compilable class.
Decompile a modern .NET console app — a dotnet new console on .NET 6 or later — and go looking for static void Main. It is not there. What you find instead is an internal class Program you never wrote, holding a method you cannot even type into a C# file: <Main>$. Your actual code, the handful of statements you put at the top of Program.cs, is sitting inside it. This is the shape of top-level statements, and reconstructing the file you wrote out of it is a small, exact piece of decompiler work that goes wrong in an obvious way if the tool does not know the pattern.
The real question
Top-level statements let you drop executable code at file scope with no class and no method around it. The runtime, though, still needs a type with an entry-point method — the CLR has no concept of “a loose statement”. So the compiler must manufacture that type and that method, and it must do so with names that cannot clash with anything you might legally write. Then a decompiler has to walk it back: from a Program class and a <Main>$ method to a file that has neither. Get the recognition wrong and you emit C# that will not compile, because <Main>$ is not a legal identifier. So where exactly does your code go, what do the synthesized names look like, and how does a reader know to undo them?
What the compiler actually emits
Here is a small program that uses the features worth tracing — the implicit args, a top-level await, an int return, and a local function:
using System.Net.Http;
if (args.Length > 0)
Console.WriteLine($"first arg: {args[0]}");
using var client = new HttpClient();
string body = await client.GetStringAsync("https://example.com");
Console.WriteLine(Summarize(body));
return body.Length == 0 ? 1 : 0;
static string Summarize(string s) => $"{s.Length} bytes";
No namespace, no class, no method. Compile it and open the metadata, and the compiler’s scaffolding is in plain view:
.class private auto ansi beforefieldinit Program
extends [System.Runtime]System.Object
{
.custom instance void [System.Runtime]...CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.method private hidebysig static
class [System.Runtime]System.Threading.Tasks.Task`1<int32> '<Main>$' (string[] args) cil managed
{
.custom instance void ...AsyncStateMachineAttribute::.ctor(class [...]System.Type)
= ( 01 00 15 50 72 6f 67 72 61 6d 2b 3c 3c 4d 61 69 6e 3e 24 3e 64 5f 5f 30 00 00 )
// ↑ typeof(Program+<<Main>$>d__0)
}
.method private hidebysig specialname static int32 '<Main>' (string[] args) cil managed
{
.entrypoint
// body: <Main>$(args).GetAwaiter().GetResult()
}
.method assembly hidebysig static string '<<Main>$>g__Summarize|0_0' (string s) cil managed { }
// nested: .class ... sealed '<<Main>$>d__0' extends ValueType implements IAsyncStateMachine
}
Several things are worth reading slowly here.
The type is Program — a speakable name. It is internal and marked [CompilerGenerated], but the compiler deliberately did not mangle it. The name is reused on purpose: you are allowed to write partial class Program { … } in your own file to add members, and the two halves only merge if they share the exact name Program. So the type keeps a legal identifier.
The method is <Main>$ — an unspeakable name. A method cannot be split across files the way a partial class can, so the compiler protects it from collision the other way: by giving it a name with <, > and $ in it. That is legal in IL but illegal in C#, which guarantees it can never clash with a Main you write, and guarantees you cannot call it by name. This asymmetry — speakable type, unspeakable method — is the fingerprint. The one piece of metadata that says “this came from top-level statements” is a [CompilerGenerated] type containing a static method literally named <Main>$.
args is a real parameter. The implicit args you used in the source is nothing magical — it is the ordinary string[] args parameter of <Main>$, and the compiler just lets top-level code see it by name.
The await splits the entry point in two
The most interesting detail is what the top-level await did. Because the body awaits, <Main>$ is not static int — it is static async Task<int>, carrying [AsyncStateMachine(typeof(Program+<<Main>$>d__0))] and lowered into the generated struct <<Main>$>d__0 the same way any async method is. (That struct — <>1__state, <>t__builder, the hoisted <client>5__2, the <>u__1 awaiter — is a story of its own, told in how Glass rebuilds an async iterator state machine.)
But the CLR entry point cannot be an async method. So the compiler synthesized a second method, <Main> — note the name: angle brackets, but no $ — marked .entrypoint and specialname, returning int32. Its whole body is the synchronous drive of the async one:
.method private hidebysig specialname static int32 '<Main>' (string[] args) cil managed
{
.entrypoint
ldarg.0
call class Task`1<int32> Program::'<Main>$'(string[])
callvirt instance valuetype TaskAwaiter`1<int32> Task`1<int32>::GetAwaiter()
stloc.0
ldloca.s 0
call instance !0 TaskAwaiter`1<int32>::GetResult()
ret
}
So a top-level program with await has two entry-ish methods: the real .entrypoint (<Main>, synchronous, blocks) and the async one that holds your code (<Main>$). Without the await, there is only one — <Main>$ itself carries .entrypoint and returns void or int, and there is no wrapper and no state machine. Knowing both shapes is what keeps a decompiler from printing the plumbing.
csc wraps file-scope code in a speakable Program class and an unspeakable <Main>$ method (plus a synchronous .entrypoint wrapper and a state machine once an await is present); Glass matches that fingerprint and prints the original top-level file back.How Glass maps it back
Glass does not guess from heuristics like “the class is called Program”. It keys off the one name the compiler guarantees — the unspeakable <Main>$ method — and then runs a fixed reconstruction:
- Match the fingerprint. A
[CompilerGenerated]type containing a static method whose metadata name is<Main>$. The containing type is almost alwaysProgram, but Glass trusts the method name, not the type name, because a user can rename nothing here but can add apartial class Program. - Pick the real body. If
<Main>$returnsTask/Task<int>and carries[AsyncStateMachine], the top-level code lives in the reconstructed async body of<Main>$, and the separate<Main>method marked.entrypointis just the synchronousGetAwaiter().GetResult()wrapper — Glass identifies it by that exact body shape and drops it. If there is no state machine,<Main>$is itself the.entrypointand holds the body directly. - Promote to file scope. The statements inside
<Main>$become the file’s top-level statements; theProgramwrapper class disappears;argsis left as the implicit parameter rather than being surfaced; and if the method was async, theawaitis restored andasyncevaporates (there is noasynckeyword at file scope — the top-levelawaitis enough). - Restore the local functions. Each
<<Main>$>g__Name|n_mmethod is folded back into the local functionNameit came from and placed at the bottom of the file, exactly where a top-level local function must go.
From the CLI it is one command — point Glass at the assembly and ask for the synthesized entry point:
$ glass export ./tls.dll --member "M:Program.<Main>$(System.String[])"
You get the original top-level file: the if (args.Length > 0), the await client.GetStringAsync(...), the return, and static string Summarize(...) at the end — no Program, no <Main>$, and crucially nothing that fails to compile. Add --il and Glass shows the honest other side: the Program class, the <Main>$ and <Main> pair, and the <<Main>$>d__0 struct the C# view hides.
Caveats and where it gets subtle
Three honest edges. First, if you declared your own partial class Program with real members, those members are yours — Glass keeps them as a normal partial class Program and only unwraps the synthesized <Main>$ half, so the output is a top-level file plus your partial class, which is exactly what you wrote. Second, a program that reads its exit code through Environment.Exit or has no top-level await has no wrapper and no state machine, so the shape is simpler and the reconstruction is just “promote <Main>$ to file scope” — but a tool that was only taught the async shape can trip here, which is why both paths matter. Third, the <Main>$ name is a compiler convention, not a runtime guarantee; a non-Roslyn producer, or hand-written IL that names its entry point Main the ordinary way, is simply a classic static Main program and Glass prints it as a normal class — top-level reconstruction only fires on the real fingerprint.
Takeaway
Top-level statements are pure compiler sugar, and the sugar has a precise metadata shape. Your file-scope code is wrapped in a [CompilerGenerated] class named Program — speakable, so you can extend it with partial class Program — and an entry-point method named <Main>$ — unspeakable, so it can never collide with your own Main. args is that method’s ordinary parameter, local functions lower to <<Main>$>g__… members, and a single top-level await turns <Main>$ into an async state machine with a separate synchronous .entrypoint wrapper beside it. Glass.NET recognises the <Main>$ fingerprint, unwraps the class, drops the wrapper, restores the await and the local functions, and prints the top-level file you actually wrote — compilable C#, not an un-compilable class full of <…>$ names — all as static analysis, without running a line. Grab the free build from the Glass.NET download page and open the next dotnet new console you need to read.
Try Nebula.NET
Harden your .NET code in minutes — start with the free edition.