As Sriram Sakthivel's answer says the issue is due to lack of boxing and accidentally the list enumerator implementation being a struct
, not a reference type. Usually, one would not expect the value-type behavior for an enumerator, as most are either exposed by the IEnumerator
/IEnumerator<T>
interfaces, or are reference types themselves. A quick way to go around this is to change this line
var enumerators = myIntsGrid.Select(c => c.GetEnumerator()).ToList();
to
var enumerators
= myIntsGrid.Select(c => (IEnumerator) c.GetEnumerator()).ToList();
instead.
The above code will construct a list of already boxed enumerators, which will be treated as reference type instances, because of the interface cast. From that moment on, they should behave as you expect them to in your later code.
If you need a generic enumerator (to avoid casts when latter using the enumerator.Current
property), you can cast to the appropriate generic IEnumerator<T>
interface:
c => (IEnumerator<int>) c.GetEnumerator()
or even better
c => c.GetEnumerator() as IEnumerator<int>
The as
keyword is said to perform a lot better than direct casts, and in the case of a loop it could bring an essential performance benefit. Just be careful that as
returns null
if the cast fails As per Flater's request from comments:. In the OP's case, it is guaranteed the enumerator implements IEnumerator<int>
, so it is safe to go for an as
cast.