#573 – Array Covariance Doesn’t Apply to Value Types

Array covariance allows T[] to be assigned to U[], if 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;
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #573 – Array Covariance Doesn’t Apply to Value Types

  1. geoffmazeroff says:

    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

  2. geoffmazeroff says:

    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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: