Why anonymous methods inside structs can not access instance members of 'this'

c#

Solution

Variables are captured by reference (even if they were actually value-types; boxing is done then).

However, `this` in 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

- The Truth About Value Types

Note in response to the comment by Chris Sinclair:

As a quick fix, you can store the struct in a local variable: `A thisA = this; var items = Enumerable.Range(0, 10).Where(i => i == thisA._field);` – Chris Sinclair 4 mins ago

Beware of the fact that this creates surprising situations: the identity of `thisA` is not the same as `this`. More explicitly, if you choose to keep the lambda around longer, it will have the boxed copy `thisA` captured by reference, and not the actual instance that `SomeMethod` was called on.

Problem

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.

Original source

Related problems