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; };
}
}
}
You are implementing
IEnumerable<Vehicle>, a generic interface that is strongly typed to holdVehicleobjects. That interface, however, derives from the olderIEnumerableinterace that is not generic, and is typed to holdobjectobjects.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
GetEnumeratorby 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 toIEnumerable<Vehicle>in order to use them. Instead, you probably want to do this: