I have a class heirarсhy:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyProject.Models;
using MyProject.Extensions;
namespace MyProject.Models
{
public abstract class Vehicle
{
public string Color { get; set; }
}
public class Car : Vehicle
{
public int Mileage { get; set; }
}
public class Boat : Vehicle
{
public int Displacement { get; set; }
}
}
namespace MyProject.Extensions
{
public static class VehicleExtensions
{
public static IEnumerable<Vehicle> FilterByColor(this IEnumerable<Vehicle> source, string color)
{
return source.Where(q => q.Color == color);
}
}
}
namespace MyProject.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
List<Car> cars = new List<Car>();
cars.Add(new Car() { Color = "white", Mileage = 10000 });
cars.Add(new Car() { Color = "black", Mileage = 20000 });
IEnumerable<Car> filtered = cars.FilterByColor("black");
// Compile error, can not cast IEnumerable<Vehicle> to IEnumerable<Car>
//.OfType<Car>() - only this helps. I`m looking for another ways
return View(filtered);
}
}
}
I want to use extension method on IEnumerable<Car> and get IEnumerable<Car> from it but method returns IEnumerable<Vehicle>, because it works across all derived classes – compile error. Only one way I know to fix this is to add call .OfType<Car>(), but is this a preferred way? May be there are better ways?
I suspect you just want to make it a generic method with a constraint to ensure that the type parameter is
Vehicleor a subclass: