Casting an Array of Objects to a typed Array

  • Thread starter Thread starter Phil Jones
  • Start date Start date
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.
 
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.
 
Back
Top