#568 – Array Covariance
April 24, 2012 4 Comments
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;
Pingback: #574 – The Problem with Array Covariance « 2,000 Things You Should Know About C#
Pingback: #1,065 – Cases When Array Covariance Doesn’t Work | 2,000 Things You Should Know About C#
Pingback: #1,146 – Generics Don’t Support Covariance | 2,000 Things You Should Know About C#
Pingback: #1,147 – Why Generics Don’t Support Covariance | 2,000 Things You Should Know About C#