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; };
}
}
}
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 .
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With