I am implementing ICollection< T > and there are problems doing enumerator implementation.
I understand that IEnumerator< T > has to implement IEnumerator for back-compatibility (.NET 1.0)
But If i am implementing IEnumerator< T >, then there are 2 Current Properties.
I have 2 questions:
-
What should be their relation ? Is following code correct ?
T IEnumerator<T>.Current { get { if (_cursor < 0 || _cursor >= _array.Length) throw new InvalidOperationException("Iterator position invalid"); else return _array[_cursor]; } } object IEnumerator.Current { get { return IEnumerator<T>.Current; } }
I get this error: An object reference is required for the non-static field, method, or property ‘System.Collections.Generic.IEnumerator.Current.get’
(2). Why IEnumerator< T > has to implement IDisposable. Dispose is for unmanaged resources, but in what scenario in-general would Enumerator use unmanaged resources ?
There are several cases where it’s useful that
IEnumerator<T>inherits fromIDisposable.For example take
File.ReadLines()which needs to keep open aFileStream, which is an unmanaged resource.Or if you think about an iterator using the
yield syntaxyou needIDisposableto make finally clauses work correctly:Typically you’d implement
Currentlike this:Your original code doesn’t work since you try to get a static property on the interface itself. You probably wanted to to
((IEnumerator<T>)this).Current. But if you implementT Current{...}implicitly you don’t need that cast at all.