c# - Deep diving into the implementation of closures -


consider following code block:

int x = 1; d foo = () => {     console.writeline(x);     x = 2; };  x = 3; foo(); console.writeline(x); 

the output is: 3,2. i'm trying understand happens behind scenes when code running.

the compiler generates new class: enter image description here

the question if how x variable get's changed. how x inside <>_diplayclass1 changing x inside program class. doing behind scenes?

var temp = new <>c_displayclass1(); temp.x = this.x; temp.<main>b_0(); this.x = temp.x; 

it helps @ de-compiled code:

// decompiled jetbrains decompiler // type: program // assembly: test, version=0.0.0.0, culture=neutral, publickeytoken=null // mvid: d26ff17c-3fd8-4920-befc-ed98bc41836a // assembly location: c:\temp\test.exe // compiler-generated code shown  using system; using system.runtime.compilerservices;  internal static class program {   private static void main()   {     program.\u003c\u003ec__displayclass1 cdisplayclass1 = new program.\u003c\u003ec__displayclass1();     cdisplayclass1.x = 1;     // issue: method pointer     action action = new action((object) cdisplayclass1, __methodptr(\u003cmain\u003eb__0));     cdisplayclass1.x = 3;     action();     console.writeline(cdisplayclass1.x);   }    [compilergenerated]   private sealed class \u003c\u003ec__displayclass1   {     public int x;      public \u003c\u003ec__displayclass1()     {       base.\u002ector();     }      public void \u003cmain\u003eb__0()     {       console.writeline(this.x);       this.x = 2;     }   } } 

specifically, @ how main got re-written:

  private static void main()   {     program.\u003c\u003ec__displayclass1 cdisplayclass1 = new program.\u003c\u003ec__displayclass1();     cdisplayclass1.x = 1;     // issue: method pointer     action action = new action((object) cdisplayclass1, __methodptr(\u003cmain\u003eb__0));     cdisplayclass1.x = 3;     action();     console.writeline(cdisplayclass1.x);   } 

you see x being affected attached closure class generated code. following line changes x 3:

    cdisplayclass1.x = 3; 

and same x method behind action referring to.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -