Skip to content

Instantly share code, notes, and snippets.

@mterwoord
Last active November 16, 2016 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mterwoord/1fdca9a317a96d808b209e08400dc8ed to your computer and use it in GitHub Desktop.
Save mterwoord/1fdca9a317a96d808b209e08400dc8ed to your computer and use it in GitHub Desktop.
Closures
int i = 1;
Action<string> x = s => Console.WriteLine("i = {0}, s = '{1}'", i, s);
x("Hello, World");
i = 2;
x("Hello, World");
IL:
IL_0000: nop
IL_0001: newobj UserQuery+<>c__DisplayClass0_0..ctor
IL_0006: stloc.0 // CS$<>8__locals0
IL_0007: nop
IL_0008: ldloc.0 // CS$<>8__locals0
IL_0009: ldc.i4.1
IL_000A: stfld UserQuery+<>c__DisplayClass0_0.i
IL_000F: ldloc.0 // CS$<>8__locals0
IL_0010: ldftn UserQuery+<>c__DisplayClass0_0.<Main>b__0
IL_0016: newobj System.Action<System.String>..ctor
IL_001B: stloc.1 // x
IL_001C: ldloc.1 // x
IL_001D: ldstr "Hello, World"
IL_0022: callvirt System.Action<System.String>.Invoke
IL_0027: nop
IL_0028: ldloc.0 // CS$<>8__locals0
IL_0029: ldc.i4.2
IL_002A: stfld UserQuery+<>c__DisplayClass0_0.i
IL_002F: ldloc.1 // x
IL_0030: ldstr "Hello, World"
IL_0035: callvirt System.Action<System.String>.Invoke
IL_003A: nop
IL_003B: br.s IL_003D
IL_003D: ret
<>c__DisplayClass0_0.<Main>b__0:
IL_0000: ldstr "i = {0}, s = '{1}'"
IL_0005: ldarg.0
IL_0006: ldfld UserQuery+<>c__DisplayClass0_0.i
IL_000B: box System.Int32
IL_0010: ldarg.1
IL_0011: call System.Console.WriteLine
IL_0016: nop
IL_0017: ret
<>c__DisplayClass0_0..ctor:
IL_0000: ldarg.0
IL_0001: call System.Object..ctor
IL_0006: nop
IL_0007: ret
IL release mode:
IL_0000: newobj UserQuery+<>c__DisplayClass0_0..ctor
IL_0005: dup
IL_0006: ldc.i4.1
IL_0007: stfld UserQuery+<>c__DisplayClass0_0.i
IL_000C: dup
IL_000D: ldftn UserQuery+<>c__DisplayClass0_0.<RunUserAuthoredQuery>b__0
IL_0013: newobj System.Action<System.String>..ctor
IL_0018: stloc.0 // x
IL_0019: ldloc.0 // x
IL_001A: ldstr "Hello, World"
IL_001F: callvirt System.Action<System.String>.Invoke
IL_0024: ldc.i4.2
IL_0025: stfld UserQuery+<>c__DisplayClass0_0.i
IL_002A: ldloc.0 // x
IL_002B: ldstr "Hello, World"
IL_0030: callvirt System.Action<System.String>.Invoke
IL_0035: ret
<>c__DisplayClass0_0.<RunUserAuthoredQuery>b__0:
IL_0000: ldstr "i = {0}, s = '{1}'"
IL_0005: ldarg.0
IL_0006: ldfld UserQuery+<>c__DisplayClass0_0.i
IL_000B: box System.Int32
IL_0010: ldarg.1
IL_0011: call System.Console.WriteLine
IL_0016: ret
<>c__DisplayClass0_0..ctor:
IL_0000: ldarg.0
IL_0001: call System.Object..ctor
IL_0006: ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment