3

I have a Fleet class that contains an array of (base class) Vehicles. The vehicles in the array are subclasses of Vehicles: Plains, Trains and Automobiles. The array is private, but the Fleet class must offer a method to get at the vehicles of a given type.

Something like:

class Fleet
{
    private Vehicle[] _vehicles;

    // returns the vehicles of the specified subclass
    public ???? Get(????)
    {
        return ????
    }
}

Fleet fleet = new Fleet("fleet.def");

Trains[] trains = fleet.Get(Trains);   // looks clean but isn't possible
Plains[] plains = fleet.Get<Plains>(); // looks okay but don't know
                                       //   how to implement

(I'm using arrays, but really any collection type that can be iterated is fine.)

Now, as you can see, I have absolutely no idea how to implement this. I'm looking for an elegant solution for the Get method, efficiency is not really an issue. Please also name the key techniques involved in the solution, so I can look them up in my C# books...

Thanks!

3 Answers 3

12

Your Fleet.Get() will look like

public IEnumerable<T> Get<T>()
{
  return _vehicles.OfType<T>();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot dh! Looks very clean. Now I can use "foreach (Plain plain in fleet.Get<Plain>()) { }. I guess that I can also use .ToList() and .ToArray() to store the result in a variable? What is this technique with the angle brackets called (yes, I am a n00b and not ashamed of it)?
That's called generics. The idea is to substitute a concrete type for reusability (for example when you have similar operations over different types). You can find out more in Introduction to Generics at msdn.microsoft.com/en-us/library/0x6a29h6.aspx
Hmm, that's quite a generic name for such a specific thing :-) Thanks again, I have some reading to do...
1

Make it a List<> and use FindAll(x => x.GetType() == typeof(Train)) to get all Train objects from the list.

Comments

0
 public T[] Get<T>() where T : Vehicle
 {
     List<Vehicle> lstVehicles = new List<Vehicle>(_vehicles);
     return lstVehicles.FindAll(delegate(Vehicle vehicle){
         return vehicle.GetType() == typeof(T);
     }).ToArray();
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.