1

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?

flag

75% accept rate

3 Answers

1
using System.Linq;

newObjects = objects.Select(eachObject => (ClassA)eachObject).ToArray();
link|flag
Thanks. This is what i was looking for. – malay Jul 15 '09 at 14:31
2

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

newObjects = objects.Cast<ClassA>().ToArray();
link|flag
This is even better. Thanks – malay Jul 16 '09 at 5:57
2

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.

link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.