tags:

views:

277

answers:

4

If Dog enherits from Animal.

And I have a Animal[], that I happen to know contains only dogs. What's the fastest/best way to get my hands on a Dog[] ? I've used new ArrayList(oldarray).ToArray(typeof(Dog)); so far, but that feels a bit clumsy, and I'm wondering if there is something more elegant.

UPDATE: Using the .net 2.0 profile. Should have offcourse mentioned this straight away. I hope editing the original question adheres to the stackoverflow netiquette in this case. I'm looking forward to the day where we can upgrade and use Linq.

Bye, Lucas

+10  A: 
var dog_arr = Array.Convert(animal_arr, x => (Dog) x);
leppie
I had to use Array.ConvertAll. Other than that I really like the elegance of this solution.
Daver
+6  A: 

Using LINQ this will be

oldarray.Cast<Dog>().ToArray();
Alexander Prokofyev
while this is elegant, it's also very inefficient IMHO
Philippe Leybaert
+2  A: 

Perhaps you are able to create it as a Dog[] array in the first place?

Given:

interface ICage {
    Animal[] GetAnimals();
}

If you instantiate a Animal[] array with Dogs in it, you cannot cast the array:

class DogCage : ICage {
    Animal[] GetAnimals() { return new Animal[] { spot, fido }; }
}

If you instantiate a Dog[] array with Dogs in it, it can still be returned as Animal[] array, but you can also cast the array back to Dog[].

class DogCage : ICage {
    Animal[] GetAnimals() { return new Dog[] { spot, fido }; }
}

Now this will work:

Dog[] dogs = (Dog[])cage.GetAnimals();
Hallgrim
A: 

You could use a generic collection e.g. List from System.Collections.Generic instead of an array then use the following:

List<Animal> animals = new List<Animal>();
animals.Add(new Dog());
List<Dog> dogs = animals.ConvertAll(delegate(Animal animal) { return (Dog)animal; });

If you really needed it in an array you could also do:

animals.ConvertAll(delegate(Animal animal) { return (Dog)animal; }).ToArray();
mdresser