Passing collections of derived objects in C#

c#, collections, inheritance

Solution

No, that's not possible.

So if we have a function that accepts a `List<Car>` types. Clearly that function ought to be able to add a `Prius` to that list, no? Well, if you were allowed to pass a `List<Mustang>` to this method you'd have just added a `Prius` to a `List<Mustang>`, clearly that would be bad.

Now if, rather than passing a `List`, the method had a parameter of `IEnumerable` or one of certain other read only collection types then it's possible it's "covariant". In that case, you could accept, as an example, an `IEnumerable<Car>` and pass it a `List<Mustang>` because you're never adding to the list, you're only accessing various elements, and as long as all of the `Mustang` objects are `Car` objects that's not a problem.

The design also seems a bit...off. I wouldn't think that `Ford` should inherit from `Car`. `Ford` isn't a car, it's a brand, a company, a type of car. `Mustang` is a car, so it makes sense for it to inherit from one. I would create a new type, say `Manufacturer` of which you could create `Ford`, `Toyota`, etc. and make that a (read only) property of `Car`.

Problem

I'm still getting my feet wet with OO and C#. I'm sure this is a simple question and I think I know the answer, but I want to be sure. If I have a class called `Car` and another class called `Ford` which inherits from `Car`, and yet another class called `Mustang` which inherits from the `Ford` class. Is it acceptable/possible to create a method that accepts a collection of `Car` objects and then when I call that method actually pass to that method a collection of `Mustang` (or `Ford`) objects since they are in fact `Car` objects? My thought is that this should be possible, with the understanding that I would only be able to access Properties\Methods of the `Car` class. Am I way off base on this? Also, if I am right, that you can do this: do you need to cast the `Mustang` collection to a `Car` collection in the call to the method?

Original source