I have an interesting issue where a class inherits from a class that implements IEnumerable, but I also want the class to implement IEnumerable for a different type. Everything works except for IEnumerable extension methods, which means I can’t do any LINQ to objects by default without always having to cast first. Does anyone have any ideas besides constantly casting?
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqTesting
{
public class Trucks<T> : Vehicles, IEnumerable<Truck>
{
public Trucks()
{
// Does Compile
var a = ((IEnumerable<Truck>)this).FirstOrDefault();
// Doesn't Compile, Linq.FirstOrDefault not found
var b = this.FirstOrDefault();
}
public new IEnumerator<Truck> GetEnumerator() { throw new NotImplementedException(); }
}
public class Vehicles : IEnumerable<Vehicle>
{
public IEnumerator<Vehicle> GetEnumerator() { throw new NotImplementedException(); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
}
public class Vehicle { }
public class Truck : Vehicle { }
}
Actually you can, but you can’t take the advantage of generic types inference, because your class implements two
IEnumerable<T>of two different types and the compiler can’t know which type you want to use.You can specify it direclty, like: