views:

296

answers:

3

I want to upcast object array to different array of different object type like below

object[] objects; // assuming that it is non-empty

CLassA[] newObjects = objects as ClassA[]; // assuming that object to ClassA is valid upcasting

is there any way other than upcasting each element individually?

+1  A: 
using System.Linq;

newObjects = objects.Select(eachObject => (ClassA)eachObject).ToArray();
zvolkov
Thanks. This is what i was looking for.
malay
+2  A: 

Or I guess you could try something like this for even shorter syntax:

newObjects = objects.Cast<ClassA>().ToArray();
zvolkov
This is even better. Thanks
malay
+2  A: 

As this post suggests, you may be able to do the following trick (untested):

newObjects = (ClassA[])(object)objects;

Note that in C# 4.0 you won't need to cast, you will be able to directly assign newObjects = objects.

zvolkov