Easy way to cast an object array into another type in C#
Posted
by Na7coldwater
on Stack Overflow
See other posts from Stack Overflow
or by Na7coldwater
Published on 2010-06-12T22:28:26Z
Indexed on
2010/06/12
22:32 UTC
Read the original article
Hit count: 144
I want to be able to be able to quickly cast an array of objects to a different type, such as String, but the following code doesn't work:
String[] a = new String[2];
a[0] = "Hello";
a[1] = "World";
ArrayList b = new ArrayList(a);
String[] c = (String[]) b.ToArray();
And I don't want to have to do this:
String[] a = new String[2];
a[0] = "Hello";
a[1] = "World";
ArrayList b = new ArrayList(a);
Object[] temp = b.ToArray();
Object[] temp = b.ToArray();
String[] c = new String[temp.Length];
for(int i=0;i<temp.Length;i++)
{
c[i] = (String) temp[i];
}
Is there an easy way to do this without using a temporary variable?
© Stack Overflow or respective owner