when I go to the definition of List<> I can see it has a public struct Enumerator that implements the interfaces IEnumerator<T>
, IDisposable and IEnumerator.
IEnumerator should force the implementation of Reset - besides Current and MoveNext. Yet only Current and MoveNext are implemented.
How can that be?
Where do I find the Reset() of List<>?
var list = new List<int>();
list.Add(23);
list.Add(44);
var Enumerator = list.GetEnumerator();
while (Enumerator.MoveNext())
{
Console.WriteLine(Enumerator.Current);
}
Enumerator.
And when I try it in code there is no Reset():
Ok - I tried to show a screenshot, but they don't let me.
But copying above code shows no Reset-Method after the Dot-operator (.) of Enumerator.
Would someone know and throw some light on this?
I see it calls the Reset of IEnumerator which is part of mscorlib.
var list = new List<int>();
list.Add(23);
list.Add(44);
var Enumerator = list.GetEnumerator();
Enumerator.MoveNext();
Enumerator.MoveNext();
Console.WriteLine(Enumerator.Current);
((IEnumerator<int>)Enumerator).Reset();
Enumerator.MoveNext();
And yet as IEnumerator is an interface how can code be called by it?
Reset() in IEnumerator should just be a definition and the implementation left to whoever uses the interface.
But somehow here actual functionality is provided by just defining the interface to be implemented. Nowhere do I see the actual implementation - and that part I do not understand.
It's explicitly implemented, as shown in the documentation, as is IEnumerator.Current
. In other words, you can only call the method on a value with a compile-time type of IEnumerator
.
So you could use:
// Casing changed to be more conventional
var enumerator = list.GetEnumerator();
((IEnumerator)enumerator).Reset();
However, that would then box the value anyway (as List<T>.Enumerator
is a struct) which would make it pointless. It's not clear whether you're just interested in the apparent lack of a Reset
method, but in general I would strongly advise you not to rely on IEnumerator.Reset
- it's very often not implemented, and IMO it shouldn't have been part of the interface to start with...
See more on this question at Stackoverflow