2

Why in this MSDN example is needed the GetEnumerator1 method?

// Must implement GetEnumerator, which returns a new StreamReaderEnumerator. 
public IEnumerator<string> GetEnumerator()
{
    return new StreamReaderEnumerator(_filePath);
}

// Must also implement IEnumerable.GetEnumerator, but implement as a private method. 
private IEnumerator GetEnumerator1()
{
    return this.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator1();
}

1 Answers1

0

No need, we can just use

// Must implement GetEnumerator, which returns a new StreamReaderEnumerator. 

public IEnumerator<string> GetEnumerator()
{
    return new StreamReaderEnumerator(_filePath);
}

// Must also implement IEnumerable.GetEnumerator, but implement as a private method. 

IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

instead.

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
  • Thanks for the reply, that was exactly what I was thinking, but I have a doubt... the `return GetEnumerator();` will not end calling recursively the `IEnumerator IEnumerable.GetEnumerator()` method? –  Oct 30 '14 at 03:37
  • 2
    @gsc-frank, it won't. To make it recursive you need to cast it to `IEnumerable`: `return ((IEnumerable)this).GetEnumerator();` – Kirill Polishchuk Oct 30 '14 at 04:13