Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array of objects

how can i convert from:

object[] myArray

to

Foo[] myCastArray
like image 822
leora Avatar asked Dec 13 '22 04:12

leora


1 Answers

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.

like image 164
mmx Avatar answered Dec 30 '22 00:12

mmx