I have a code like the following:
struct A
{
void SomeMethod()
{
var items = Enumerable.Range(0, 10).Where(i => i == _field);
}
int _field;
}
… and then i get the following compiler error:
Anonymous methods inside structs can not access instance members of ‘this’.
Can anybody explains what’s going on here.
Variables are captured by reference (even if they were actually value-types; boxing is done then).
However,
thisin a ValueType (struct) cannot be boxed, and hence you cannot capture it.Eric Lippert has a nice article on the surprises of capturing ValueTypes. Let me find the link
Note in response to the comment by Chris Sinclair:
Beware of the fact that this creates surprising situations: the identity of
thisAis not the same asthis. More explicitly, if you choose to keep the lambda around longer, it will have the boxed copythisAcaptured by reference, and not the actual instance thatSomeMethodwas called on.