#572 – Why Array Covariance Is Called Covariance

Array covariance in C# allows you to assign an array of instances of a derived class to a variable whose type is an array of instances of the base class.

Dog[] dogs = hounds;     // Where hounds is Hound[] and Hound is subclass of Dog

Covariance says that the ordering of two elements in a set is preserved after transforming each by the same function.

With array covariance, we can think of the “ordering” as being the fact that the subtype is narrower than the base class, which means that the assignment is allowed due to assignment compatibility.

The covariant function being applied to each type is to create an array of that type.  This “function”, an array of a type, is then covariant because if type T is narrower than type U, then T[] is also narrower than U[], preserving assignment compatibility.

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

Leave a comment