Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement IEnumerable<T> with GetEnumerator()? [duplicate]

Tags:

c#

ienumerable

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'.

like image 264
Colonel Panic Avatar asked Jul 03 '12 14:07

Colonel Panic


People also ask

What is IEnumerator IEnumerable GetEnumerator ()?

IEnumerable is an interface that allows us to iterate over a collection; it does so by exposing a single GetEnumerator() method, which in turn returns an IEnumerator: a simple interface that provides methods to access the current element in the collection, move to the next item, and reset back to the beginning of the ...

How do you implement an enumerator?

When you type public class Simulation : IEnumerable<string> , 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.

What is GetEnumerator?

The C# GetEnumerator() method is used to convert string object into char enumerator. It returns instance of CharEnumerator. So, you can iterate string through loop.


2 Answers

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();
    }
}
like image 109
Filip Ekberg Avatar answered Sep 23 '22 06:09

Filip Ekberg


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).

like image 29
NominSim Avatar answered Sep 21 '22 06:09

NominSim