I cannot create an iterator class with Ienumerable<T>

Asked

Viewed 38 times

1

I’m creating an iterator class - has support for foreach - implementing the interface IEnumerable<T> package System.Collections.Generic, as in the code below:

public class MyList<T> : IEnumerable<T> {

    private T[] list;

    // Código...

    public IEnumerator<T> GetEnumerator() {
        for (int index = 0; index < this.list.Length; i++) {
            yield return this.list[index];
        }
    }
}

The problem is that the compiler is generating the following error:

error CS0738: "MyList<T>" não implementa membro de interface "IEnumerable.GetEnumerator()
". "MyList<T>.GetEnumerator()" não pode implementar "IEnumerable.GetEnumerator()" porqu não tem o tipo de retorno correspondente de "IEnumerator".

What’s wrong with the code? What am I doing wrong? I have revised the code several times and apparently the implementation is in accordance with the documentation.

  • https://stackoverflow.com/questions/8760322/troubles-implementing-ienumerablet

  • 1

    Related: https://answall.com/q/479755/69296

1 answer

2


No stackoverflow in English has a question similar to yours, follows the free translation of the accepted answer

Like IEnumerable<T> implements IEnumerable you need to implement this interface also in your class, which has the non-generic version of the method GetEnumerator. To avoid conflicts, you can explicitly implement it

IEnumerator IEnumerable.GetEnumerator()
{
    // chama a versão genérica do método
    return this.GetEnumerator();
}

public IEnumerator<T> GetEnumerator()
{
    for (int i = 0; i < Count; i++)
        yield return _array[i];
}
  • Just one more question. What is the advantage of using generic Ienumerable? Searching here, I saw that it is possible to use only the IEnumerable and the IEnumerator. So why does the documentation say to use generic?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.