Normally you shouldn't be able to cast arrays of any type to another, and is a bad practice to do so. For backward compatibility C# has array covariance, which allows a cast in the opposite direction, but not in the direction you want. To properly convert an array, you have to create another array, as shown in this stackoverflow post:
var attributes = (new object[]
{
new SomeClass(),
}).Cast<SomeBaseClass>().ToArray();
Why is it bad to be able to cast arrays?
Consider the following example:
class A {}
class B : A {}
...
var array_a1 = new A[] { new A(); };
var array_b1 = (B[])array_a; // This is error #1
var array_b2 = new B[] { new B(); };
var array_a2 = (A[])array_b2;
array_a2[0] = new A(); // This is error #2
In the case of error #1, it is clearly seen that array_b1
cannot be a valid view of A[]
, as it could have objects of type A when read. This is a runtime error of InvalidCastException
, happening at the time of the cast.
In the case of error #2, array_a2
is a valid view of array_b2
, but only for reading. The cast itself is allowed due to array covariance, but trying to put an element of type A in there will cause a runtime ArrayTypeMismatchException
, as it would cause array_b2
to have an element of type A. To ensure this kind of type safety the CLR has to do runtime type checks on array assignments, which affects performance.