Consider the following code creating and running anonymous delegate:
static class Program
{
static void Main(string[] args)
{
Action action = () => Console.WriteLine("Test");
action();
}
}
In .NET 5, when decompiled using ILSpy with disabled "decompile anonymous methods" option (to see the real implementation done by the compiler), it can be observed, that the code is translated to the following:
internal static class Program
{
[Serializable]
[CompilerGenerated]
private sealed class <>c
{
public static readonly <>c <>9 = new <>c();
public static Action <>9__0_0;
internal void <Main>b__0_0()
{
Console.WriteLine("Test");
}
}
private static void Main(string[] args)
{
(<>c.<>9__0_0 ?? (<>c.<>9__0_0 = <>c.<>9.<Main>b__0_0))();
}
}
Why does <Main>b__0_0
have to be an instance method on another type, rather than a static method on the Program
type? The method does not capture any local variables or state.