#574 – The Problem with Array Covariance

If we have an array of a particular base type,  assignment compatibility allows us to assign any subtype to an element of the array.

            // Dog[] can contain
            //   Dogs, or sub-classes of Dogs
            Dog[] dogs = new Dog[3];
            dogs[0] = new Dog("Lassie");
            dogs[1] = new Terrier("Jack", "Crabby");
            dogs[2] = new BorderCollie("Kirby", "Ball");

Notice, however, that the array is still of type Dog[].

Array covariance allows us to assign an array of a subtype of a class to a variable whose type is an array of the base type.

Dog[] dogs = new Terrier[3];

This can lead to a problem. What looks syntactically like an array of Dogs is really an array of Terriers.  So if we try putting any other Dog into the array, the code will compile, but we’ll get an error at run-time.

dogs[0] = new Terrier("Jack", "Snarly");      // ok
dogs[1] = new BorderCollie("Kirby", "Ball");  // Run-time error !

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.

One Response to #574 – The Problem with Array Covariance

  1. Pingback: #1,147 – Why Generics Don’t Support Covariance | 2,000 Things You Should Know About C#

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: