#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;
Thanks for shedding light on a rather confusing topic. For reference, here’s a post by Eric Lippert about why array covariance doesn’t work like one would expect:
http://blogs.msdn.com/b/ericlippert/archive/2009/09/24/why-is-covariance-of-value-typed-arrays-inconsistent.aspx
Thanks for explaining a topic that always takes me five or six times to read and understand. For reference, here’s a post by Eric Lippert about why array covariance doesn’t work as expected: http://blogs.msdn.com/b/ericlippert/archive/2009/09/24/why-is-covariance-of-value-typed-arrays-inconsistent.aspx