Casting an Array of Objects to a typed Array

P

Phil Jones

If I have an array of [Object]'s, all of the same type (say [String] for
example).

Is there a quick way to cast that to a typed String array?

Presently I'm having to copy each object to a new array. I'm wondering if
there a conversion class within the framework that makes this quick and
simple.

Cheers everyone.
 
I

Imran Koradia

Assuming the items were originally defined as the stronger type (say string
in this case) and not as type Object, you can do this for reference types
(string and others):

string[] str = (string[])objarr;

where objarr is the object array containing the strings. However, this won't
work for value types - you can use Array.Copy for value types but I would
think that would be slower than casting each item (although it would be more
concise).

object[] o = new object[]{0,1,2};
int[] i = new int[o.length];
Array.Copy(o, i, o.length];


hope that helps..
Imran.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top