I'm trying to write my own (simple) implementation of List. This is what I did so far:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace provaIEnum { class MyList<T> : IEnumerable<T> { private T[] _array; public int Count { get; private set; } public MyList() { /* ... */ } public void Add(T element) { /* ... */ } // ... public IEnumerator<T> GetEnumerator() { for (int i = 0; i < Count; i++) yield return _array[i]; } }
I'm getting an error about GetEnumerator though:
'provaIEnum.Lista' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'provaIEnum.Lista.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.
I'm not sure if I understand what VS's trying to tell me and I have no idea how to fix it.
Thanks for your time
Since IEnumerable<T>
implements IEnumerable
you need to implement this interface as well in your class which has the non-generic version of the GetEnumerator method. To avoid conflicts you could implement it explicitly:
IEnumerator IEnumerable.GetEnumerator() { // call the generic version of the method return this.GetEnumerator(); } public IEnumerator<T> GetEnumerator() { for (int i = 0; i < Count; i++) yield return _array[i]; }
Read the error message more carefully; it is telling you exactly what you must do. You did not implement System.Collections.IEnumerable.GetEnumerator
.
When you implement the generic IEnumerable<T>
you have to also implement System.Collections.IEnumerable
's GetEnumerator.
The standard way to do so is:
public IEnumerator<T> GetEnumerator () { whatever } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With