1

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.

5
  • 7
    Man, how long will it take for people to stop using ArrayList? Commented Jun 12, 2010 at 22:30
  • Hey, I'm still new to C#. What should I use instead? Commented Jun 12, 2010 at 22:47
  • Use generic collections in place of ArrayList. Generics are completely type-safe in a way that ArrayList could never possibly be. Commented Jun 12, 2010 at 22:50
  • 1
    I hope my comment wasn't taken the wrong way. It is just one of my pet peeves. Commented Jun 12, 2010 at 23:01
  • 1
    It's actually a very good questions and generics sometimes don't help at all. Let's say you have a generic piece of code running on an List<object> and a more specific one requiring a List<string>. Now another piece of code uses both methods. How would you do that? Even if you use generics all over the shop. Commented Jun 13, 2010 at 8:15

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

...and welcome to a new world ;) It's seriously worth getting your head around generics.
4

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?

Comments

1

You can do something like

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

to cast it to anything you like :)

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.