Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Troubles implementing IEnumerable<T>

Tags:

c#

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

like image 768
BlackBear Avatar asked Jan 06 '12 15:01

BlackBear


2 Answers

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]; } 
like image 185
Darin Dimitrov Avatar answered Sep 28 '22 05:09

Darin Dimitrov


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(); } 
like image 25
Eric Lippert Avatar answered Sep 28 '22 05:09

Eric Lippert