#568 – Array Covariance

In C#, you can always implicitly convert an instance of a more derived type  to an instance of a base type.

For example, the following is allowed:

Hound huck = new Hound("Huckleberry", 55);

// Since Hound is a sub-class of Dog, we can
// assign to Dog
Dog someDog = huck;

Note that at this point, the someDog variable points to an instance of a Hound, rather than an instance of a Dog.

You can also assign an array of objects of a more derived type to an array of objects of a base type.  This is known as array covariance.  It’s allowed as long as the type of the source array elements is implicitly convertible to the type of the target array elements.

Hound[] hounds = new Hound[2] {
new Hound("Huckleberry", 55),
new Hound("Astro", 50)};

// Allowed because of array covariance
Dog[] dogs = hounds;
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #568 – Array Covariance

  1. Pingback: #574 – The Problem with Array Covariance « 2,000 Things You Should Know About C#

  2. Pingback: #1,065 – Cases When Array Covariance Doesn’t Work | 2,000 Things You Should Know About C#

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

  4. 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 )

Connecting to %s

%d bloggers like this: