22

I would like my type to implement IEnumerable<string> . I tried to follow C# in a Nutshell, but something went wrong:

public class Simulation : IEnumerable<string>
{
    private IEnumerable<string> Events()
    {
        yield return "a";
        yield return "b";
    }

    public IEnumerator<string> GetEnumerator()
    {
        return Events().GetEnumerator();
    }
}

But I get the build error

Error 1 'EventSimulator.Simulation' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'EventSimulator.Simulation.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.

Colonel Panic
  • 132,665
  • 89
  • 401
  • 465

2 Answers2

41

You're missing IEnumerator IEnumerable.GetEnumerator():

public class Simulation : IEnumerable<string>
{
    private IEnumerable<string> Events()
    {
        yield return "a";
        yield return "b";
    }

    public IEnumerator<string> GetEnumerator()
    {
        return Events().GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183
  • Had a question, but @NominSim answered it in the post below - nevermind! –  Aug 15 '14 at 20:51
  • thanks, now I can add this to my EF TT file ;-) – Mike_Matthews_II Apr 27 '15 at 19:18
  • 2
    FYI, let Visual Studio type this out for you. When you type `public class Simulation : IEnumerable`, right-click on the `IEnumerable` part and go Implement Interface > Implement Interface. Visual Studio will fill in the parts of the interface that you haven't already filled in. – user2023861 Oct 02 '15 at 14:46
8

IEnumerable requires that you implement both the typed and generic method.

In the community section of the msdn docs it explains why you need both. (For backwards compatibility is the reason given essentially).

NominSim
  • 8,447
  • 3
  • 28
  • 38