views:

320

answers:

1

how can i convert from:

object[] myArray

to

Foo[] myCastArray
+10  A: 

To filter elements by Foo type:

Foo[] myCastArray = myArray.OfType<Foo>().ToArray();

To try to cast each element to Foo type:

Foo[] myCastArray = myArray.Cast<Foo>().ToArray();

Side note: Interestingly enough, C# supports a feature (misfeature?) called array covariance. It means if Derived is a reference that can be converted to Base, you can implicitly cast Derived[] to Base[] (which might be unsafe in some circumstances, see below). This is true only for arrays and not List<T> or other stuff. The opposite (array contravariance) is not true, that is, you cannot cast object[] to string[].

C# version 4.0 is going to support safe covariance and contravariance for generics too.

Example where array covariance might cause problems:

void FillArray(object[] test) {
   test[0] = 0;
}
void Test() {
     FillArray(new string[] { "test" });
}

I speculate C# has array covariance because Java had it. It really doesn't fit well in the overall C# style of doing things.

Mehrdad Afshari