Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable, requires two implementations?

Tags:

c#

interface

I am learning about implementing interfaces and generics, I made this code, but VStudio says that I did not implement System.Collections.Enumerable.GetEnumerator(). Did I not do this below, generically? It wants two implementations?

namespace Generic_cars
{
 class VehicleLot:IEnumerable<Vehicle>
 {
    public List<Vehicle> Lot = new List<Vehicle>();

    IEnumerator<Vehicle> IEnumerable<Vehicle>.GetEnumerator()
    {
        foreach (Vehicle v in Lot) { yield return v; };
    }
 }
}
like image 913
RealityDysfunction Avatar asked Oct 15 '12 02:10

RealityDysfunction


People also ask

Does list implement IEnumerable?

List implements IEnumerable, but represents the entire collection in memory. LINQ expressions return an enumeration, and by default the expression executes when you iterate through it using a foreach, but you can force it to iterate sooner using .

What is an IEnumerable?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.

When we will use IEnumerable in C#?

IEnumerable interface is used when we want to iterate among our classes using a foreach loop. The IEnumerable interface has one method, GetEnumerator, that returns an IEnumerator interface that helps us to iterate among the class using the foreach loop.


1 Answers

You are implementing IEnumerable<Vehicle>, a generic interface that is strongly typed to hold Vehicle objects. That interface, however, derives from the older IEnumerable interace that is not generic, and is typed to hold object objects.

If you want to implement the generic version (which you do) you need to also implement the non-generic version. Typically you would implement the non-generic GetEnumerator by simply calling the generic version.

Also, you probably don't want to be explicitly implementing GetEnumerator<Vehicle> the way you are; that will require you to explicitly cast your objects to IEnumerable<Vehicle> in order to use them. Instead, you probably want to do this:

public IEnumerator<Vehicle> GetEnumerator() {
    foreach( Vehicle item in items ) {
        yield return item;
    }
}

IEnumerator IEnumerable.GetEnumerator() {
    return GetEnumerator();
}
like image 90
Michael Edenfield Avatar answered Sep 22 '22 11:09

Michael Edenfield