I have a model whereby I have an abstract class (lets call it Vehicle) and several inherited classes, such as Bike, Motorbike, Car, Van etc. This is essentially a simplified version of a real world problem.
abstract class Vehicle
int ID;
int WheelCount;
string OwnerName;
class Bike
DateTime lastSafetyCheck;
class Motorbike
int EngineCC
class Car
double EngineSize
class Van
double StorageCapacity
I have within my system an IEnumerable<Vehicle> which contains each of these. This is contained in a thread safe singleton class, essentially acting as an in-memory database.
I wish to have a method in my application (in either the singleton or a seperate class) which allows me to query for only a certain type of Vehicle.
Initially I considered a method like:
internal IEnumerable<T> GetVehicles<T>() where T : Vehicle
in order that I would be able to supply a type T which would specify the type I wish to retrieve. I know that I can then use typeof() in order to perform logic. But what I cannot figure out is how to return my values? I’m basically struggling with the contents of the method, and I am beginning to think there must be a design pattern out there which would make a lot more sense.
AK
LINQ already has this method – OfType:
As an aside, to determine whether an instance is an instance of a type you do not need to use
typeof(), you can use the is and as operators (and they can be used with generic types also):Or