Click here to Skip to main content
15,884,597 members
Articles / Programming Languages / C#

C#: More On Array Variance

Rate me:
Please Sign up or sign in to vote.
4.33/5 (3 votes)
1 Aug 2010CPOL1 min read 9.9K   5  
More On Array Variance
free hit counters

In a previous post, I went through how arrays have a covariant in relation to the type of its elements, but not safely covariant.

In the following example, the second assignment is invalid at run time because, although the type of the objectArray variable is an array of object, the real type of the array is an array of string and an object cannot be assigned to a string.

C#
object[] objectArray = new string[] { "string 1", "string 2" };
objectArray[0] = "string 3";
objectArray[1] = new object();

On the other hand, because arrays are not contravariant in relation to the type of its elements, in the following code, the second line will fail at run time because string[] = object[].

C#
object[] objectArray = new object[] { "string 1", "string 2" };
string[] stringArray = (string[])objectArray;

The fact that all elements in the object array are strings doesn’t make it convertible to an array of string. To convert this object array of strings into a string array, you’ll need to create a new string array and copy each converted element.

The conversion can be made as easily as this:

C#
string[] stringArray = objectArray.Cast<string>().ToArray();

The above code is just shorthand to traversing the whole array while converting its elements to string and creating a string array with all elements.

Arrays are a good storage structure because they are the only structure provided by the runtime to store groups of items of the same type. However, because of limitations like the above, its use in APIs should be very carefully considered.

If all you need is to traverse all elements of some collection, you should use an IEnumerable<T> (IEnumerable<out T> in .NET 4.0). This way, the cost of using Enumerable.Cast<T>() is minimal.

This article was originally posted at http://feeds.paulomorgado.net/paulomorgado/blogs/en

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Paulo Morgado
Portugal Portugal

Comments and Discussions

 
-- There are no messages in this forum --