Cobertos
Cobertos

Reputation: 2253

Casting two different object arrays

I have two object arrays. One's implicitly casted by covariance from A[] to object[] and then explicitly casted back without problem. The other is an object list that I add some A's to and make an object[] from which I try to cast to A[].

public class A {}

object[] o = new A[]{new A(), new A()};
A[] a_2 = (A[])o;

List<object> lo = new List<object>();
lo.Add(new A());
lo.Add(new A());
A[] a_1 = (A[])lo.ToArray();

The second test fails with System.InvalidCastException: Cannot cast from source type to destination type. I can kind of see how this might raise an exception as we could have added anything to the object list whereas with the implicit cast, the original array must have been all As.

Is there any way to complete the second cast if the list has all As if A is not known at compile-time? Why does the second one throw the exception as, on the surface, they are both just object[] to A[] casts?

Upvotes: 0

Views: 84

Answers (2)

denys-vega
denys-vega

Reputation: 3697

Use OfType<T> function.

...
var lo = new List<object> {new A(), new A()};
var cast = lo.OfType<A>().ToArray();
...

Upvotes: 0

Peter Duniho
Peter Duniho

Reputation: 70652

No, there is no way to complete the second cast. Array variance depends on the actual type of the array object itself, not its contents. You can cast A[] to object[] array because of the array type. Note that if you try to add non-A objects to the A[] cast as object[], that still fails at run-time because the array is still an A[].

If you want an A[] object when all you have is an object[] object, you will need to create the new A[] object and copy the values from the original array to the new one.

Upvotes: 1

Related Questions