0

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.

Ivan Shimko
  • 179
  • 1
  • 9
  • 1
    Probably makes it easier to generate, as it requires less special-casing. An optimizing Jitter would probably remove `this` anyway – Charlieface Oct 31 '21 at 10:25
  • Thanks @Charlieface, could you please describe this part "An optimizing Jitter would probably remove this anyway" more? In which part of the code will this happen? – Ivan Shimko Nov 01 '21 at 07:16

0 Answers0