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
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With