struct SomeStruct
{
public int Num { get; set; }
}
class Program
{
static Action action;
static void Foo()
{
SomeStruct someStruct = new SomeStruct { Num = 5 };
action = () => Console.WriteLine(someStruct.Num);
}
static void Main()
{
Foo();
action.Invoke();
}
}
Citations from the standard will be appreciated. Any relevant online articles as well.
There will be no copies. Lambdas capture variables, not values.
You can use Reflector to look at the compile code: the compiler will move the "someStruct" variable into a helper class.
private static void Foo()
{
DisplayClass locals = new DisplayClass();
locals.someStruct = new SomeStruct { Num = 5 };
action = new Action(locals.b__1);
}
private sealed class DisplayClass
{
// Fields
public SomeStruct someStruct;
// Methods
public void b__1()
{
Console.WriteLine(this.someStruct.Num);
}
}
Copying structures will never cause user-defined code to run, so you cannot really check it that way. Actually, the code will do a copy when assigning to the "someStruct" variable. It would do that even for local variables without any lambdas.
It won't be copied, it creates a closure. Basically it'll encapsulate the structure in one object instead of creating it on the stack.
If you want to be sure you can always use reflector, but there is no need for that, the behavior is explained on Raymond Chen blog.
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