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();
}
}
- Is a copy of someStruct created when the lambda is created?
- Is a copy of someStruct created when Foo returns?
- Can I verify that copying doesn’t occur? In C++ I’d implement the copy constructor and print from inside it.
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.
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.