Passing an int array to an array in an array of objects

Why is this legal

string[] arr = new string[5]; Object[] arr2 = arr; 

But this is a compile-time error,

 int[] arr = new int[5]; Object[] arr2 = arr; 

Are int and string derived from Object? Is this a ValueType thing? If so, why is this so?

+4
source share
2 answers

The C # language provides only covariance for arrays of reference types. This is documented on MSDN :

For any two reference types A and B, if there is an implicit reference conversion (section 6.1.4) or an explicit reference conversion (section 6.2.3) between A and B, then the same reference conversion of type A [R] to array type B [R], where R is any given rank specifier (but the same for both types of arrays). This relation is known as array covariance.

In your second example, you are using an array of System.Int32 types that are not reference types, so support for array covariance is not applicable. Link types inherently store an array of links where links are the same size. The types of values ​​can be of any size, so there is no guarantee that the elements of the array will be the same size, which will prevent it from working correctly.

+2
source

This is called unsafe covariance of arrays .

It only works for arrays of reference types.

Arrays of value types are physically different sizes, so this will not work.

+3
source

Source: https://habr.com/ru/post/1490528/


All Articles