Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to cast from Animal[] to Dog[]

Tags:

arrays

c#

casting

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

like image 555
Lucas Avatar asked Jun 03 '09 11:06

Lucas


2 Answers

var dog_arr = Array.ConvertAll(animal_arr, x => (Dog) x);
like image 89
leppie Avatar answered Sep 30 '22 19:09

leppie


Using LINQ this will be

oldarray.Cast<Dog>().ToArray();
like image 40
Alexander Prokofyev Avatar answered Sep 30 '22 19:09

Alexander Prokofyev