0

With the below c# code

static void Main(string[] args)
    {
        int val = int.Parse(Console.ReadLine());
        Do (() =>
        {
            if (val == 0)
                return 1;
            return 42;
        });
    }

    public static int Do(Func<int> query)
    {
        return query();
    }

The below IL get generated

.method private hidebysig static void
    Main(
      string[] args
    ) cil managed
  {
    .entrypoint
    .maxstack 8

    IL_0000: newobj       instance void ConsoleApp1.Program/'<>c__DisplayClass0_0'::.ctor()

    // [30 13 - 30 53]
    IL_0005: dup
    IL_0006: call         string [System.Console]System.Console::ReadLine()
    IL_000b: call         int32 [System.Runtime]System.Int32::Parse(string)
    IL_0010: stfld        int32 ConsoleApp1.Program/'<>c__DisplayClass0_0'::val

    // [31 13 - 36 16]
    IL_0015: ldftn        instance int32 ConsoleApp1.Program/'<>c__DisplayClass0_0'::'<Main>b__0'()
    IL_001b: newobj       instance void class [System.Runtime]System.Func`1<int32>::.ctor(object, native int)
    IL_0020: call         int32 ConsoleApp1.Program::Do(class [System.Runtime]System.Func`1<int32>)
    IL_0025: pop

    // [39 9 - 39 10]
    IL_0026: ret

  } // end of method Program::Main

What's the purpose of IL_0000 allocation ?

How is the link between the Fun<int32> and the DisplayClass made? (I guess its the lines IL_0015 and IL_001b ?)

Lou
  • 277
  • 1
  • 5
  • 15
  • 1
    You use `val` in the delegate, so it needs to be hoisted to the heap. The `displayclass` is the container for this value – Jason Sep 19 '20 at 10:01
  • 3
    Maybe seeing it in actual C# will help: https://sharplab.io/#v2:EYLgtghgzgLgpgJwD4AEBMBGAsAKF+gAhQwHZcBvXXAmojANiIBYCBZCASwDsAKYgBgDaAXQIQEAcygBKarUo5aSgtxgEAbhAA2BALwquMAHQAFcVDg8AwgHsuUG1rhGASnAgATADLdL06QDccsoEACI2BDw80noAfMHKCiEhHABmkZo6uvr8sorJBSgkBBhB+QU0RQRMaGUFAL6BCfVU5UQAzHSMqmE2fACsADyqsQQAjgCuiACeeUpJyVWTM9F1tC049UA – Dennis_E Sep 19 '20 at 10:05
  • Also: [Why Does Code Generate MSIL Class Called <>c__DisplayClass1](https://stackoverflow.com/questions/6013094/why-does-code-generate-msil-class-called-c-displayclass1/6014613#6014613) –  Sep 19 '20 at 10:15
  • Indeed, everything becomes clear by seeing the C# version. Thanks a lot! – Lou Sep 19 '20 at 11:12

0 Answers0