Arrays Type Convertibility and Covariance

When you declare an array to contain instances of a certain reference type, the instances that you may place in that array can actually be instances of a more derived type, or any other reference type implicitly convertible to the contained type. For example, if you create an array that contains instances of type Animal, then you can feasibly insert an instance of Dog or Cat if both of them derive from Animal.

In C/C++, storing instances of type Dog or Cat into arrays as type Animal is strongly discouraged because the objects, if held by value, would get sheared off, the Cat-ness and Dog-ness would get chopped off, and all you’d end up with is Animal-ness. Not so in C#, because the array merely references the objects on the heap. If you want to make an analogy to C/C++ arrays, C# arrays are similar to C/C++ arrays holding pointers to Cat and Dog through pointers to type Animal.

You can coerce array types in another, even more interesting way:

using System;
public class Animal { }
public class Dog : Animal { }
public class Cat : Animal { }

public class EntryPoint
{
static void Main() {
Dog[] dogs = new Dog[ 3 ];
Cat[] cats = new Cat[ 2 ];
Animal[] animals = dogs;
Animal[] moreAnimals = cats;
}
}

The assignment from dogs to animals and from cats to animals is something that you definitely can’t do in native C/C++. Arrays in C# are assignable as long as their rank matches and the contained type is a reference type that is implicitly convertible from one to the other. This capability of array assignment in the CLR is provided by the fact that arrays are covariant as opposed to invariant. Both arrays in the previous example have a rank of 1, and Dog and Cat are type-convertible to Animal, thus the assignment works. The C# creators included covariant array support in the CLR primarily to support the Java language. Incidentally, this feature of the language is inherently broken and allows you to insert an instance of Table into an array of Dogs.

The full type information of an array comprises its rank (how many dimensions it has) and the type that it contains.

Source Of Information : Apress Accelerated C Sharp 2010

0 comments


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner