Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Captured Variables... What does that 'Captured' stands for actually?

In "Captured Variables" how a variable is captured?

What does that 'Captured' term stands for actually?

Does it mean referencing a value type without getting the boxing involved?

Thanks

like image 768
pencilCake Avatar asked Oct 19 '12 05:10

pencilCake


1 Answers

Captured Variables generally refers to a variable captured with a closure (basically an inline function). To "capture" means that the inline function must "capture" a reference to a variable in the outer function. To do this, the C# compiler generates a inner class and passes the outer variable by reference into the inner class (which the inline function subsequently references). You can see this if you disassemble your code.

Consider the following

void Main()
{
     string s = "hello";
     Action a = delegate 
     { 
          Debug.WriteLine(s);
     };
     s = "hello2";
     a();
} 

In the example above, the string variable s is captured by the inline Action a.

Under the hood, the C# compiler will create an inner class, which Action a references to capture the value of variable s. It's important to note that string s is passed by reference to the Action a, so the action will actually print out "hello2", not "hello". This can produce unintended side effects if not understood clearly, and is referred to as "accessing a modified closure".

like image 58
Jeff Avatar answered Oct 23 '22 11:10

Jeff