michael
michael

Reputation: 1939

C# - How to convert List<Dog> to List<Animal>, when Dog is a subclass of Animal?

I have a class Animal, and its subclass Dog. I have a List<Animal> and I want to add the contents of some List<Dog> to the List<Animal>. Is there a better way to do so, than just cast the List<Dog> to a List<Animal>, and then use AddRange?

Upvotes: 12

Views: 6955

Answers (3)

dlev
dlev

Reputation: 48596

You don't need the cast if you're using C#4:

List<Animal> animals = new List<Animal>();
List<Dog> dogs = new List<Dog>();

animals.AddRange(dogs);

That's allowed, because AddRange() accepts an IEnumerable<T>, which is covariant.

If you don't have C#4, though, then you would have to iterate the List<Dog> and cast each item, since covariance was only added then. You can accomplish this via the .Cast<T> extension method:

animals.AddRange(dogs.Cast<Animal>());

If you don't even have C#3.5, then you'll have to do the casting manually.

Upvotes: 17

Johnny5
Johnny5

Reputation: 6872

You can use Cast<T> ()

//You must have using System.Linq;

List<Dog> dogs = new List<Dog> ();
List<Animal> animals = new List<Animal> ();
animals.AddRange (dogs.Cast<Animal> ());

EDIT : As dlev points out, if you run framework 4 you don't need to cast.

Upvotes: 2

Phil
Phil

Reputation: 6679

I believe this depends on which version of .Net you're using. I could be mistaken, but in .Net 4 I think you can do

animalList.AddRange(dogList);

Otherwise in .Net 3.5, you can do

animalList.AddRange(dogList.Select(x => (Animal)x));

Upvotes: 5

Related Questions