4

how can i convert from:

object[] myArray

to

Foo[] myCastArray

1 Answer 1

13

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.