Na7coldwater
Na7coldwater

Reputation: 1414

Easy way to cast an object array into another type in C#

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();
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? Edit: This is in ASP.NET, by the way.

Upvotes: 1

Views: 497

Answers (4)

Marius Schulz
Marius Schulz

Reputation: 16440

+1 for the generic Collections such as List<T>, -1 for ArrayList which is better be put on mothballs.

Upvotes: 0

tzaman
tzaman

Reputation: 47770

Use LINQ:

String[] c = b.Cast<String>().ToArray();

May I ask why you're using ArrayList in the first place, instead of a generic collection type?

Upvotes: 4

ChaosPandion
ChaosPandion

Reputation: 78262

The best solution would be to use a List<string>.

Upvotes: 6

Diego Pereyra
Diego Pereyra

Reputation: 417

You can do something like

myArray.Select(mySomething => new SomethingElse(mySomething)).ToArray() 

to cast it to anything you like :)

Upvotes: 1

Related Questions