I tried to debug your code and noticed that
listEnum
and
iEnum
have different types. Looking at MSDN's documentation, the type of return value for
List<T>.Enumerator[
^] is
System.Collections.Generic.List<T>.Enumerator[
^], which is a
struct
. So every time you call the method, you pass a new copy to it, and that only the copy gets updated. On the other hand,
iEnum
has a type of
System.Collections.Generic.IEnumerator<T>[
^], which is an
interface
.
[Edit]In reply to comment of OP:
dybs wrote:
both List.GetEnumerator and the explicit interface implementation were simply return new Enumerator(this);
I agree that both method points to that code. However,
ICollection<T>
has inherited its
GetEnumerator
method from
IEnumerable<T>
. If you take a look at the source code for that interface, you can see that there is a method of type
IEnumerator<T>
. So basically, what happens is that, for
iEnum
, you are boxing the struct(which is a value type) to a reference type, where as, for
listEnum
, the value is a struct, since you are calling
List<T>.GetEnumerator()
directly. Below is the interface declaration of
IEnumerable<T>
public interface IEnumerable<T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}
You might also find
this post[
^] useful.
[/Edit]