#573 – Array Covariance Doesn’t Apply to Value Types
May 1, 2012 2 Comments
Array covariance allows T[] to be assigned to U[], if T can be assigned to U.
// Assignment compatibility, because Terrier is sub-type of Dog
Terrier t = new Terrier("Bob");
Dog d = t;
// Allowed because of array covariance
Terrier[] terriers = MakeTerrierArray();
Dog[] dogs = terriers;
This does not work, however, if the contents of the arrays are value types. Arrays of value-typed objects are not covariant.
byte b1 = 12;
ushort u1 = b1; // Assignment compatible
byte[] bytearray = new byte[] { 1, 2, 3 };
// Not allowed. Compile-time error "Cannot implicitly convert type 'byte[]' to 'ushort[]'
ushort[] shortarray = bytearray;
