
.NET 3.0+C# Implicitly Typed Arrays (2)
With C# 3.0, Microsoft introduced the concept of implicitly typed arrays to the language. With such an array, the type is not specified explicitly in the code. Instead, the compiler decides upon the type to use based upon the array's initial values.
Limitations
The main limitation of implicitly type arrays is that every item in the array must be of a compatible type and that at least one element of that type must appear within the initializer. This leads to workarounds being required in some situations. In the following example, the developer wishes to create an array of nullable integers. However, as the initializer does not contain a nullable integer, the code fails to compile.
var nullables = new [] { 1, 2, 3, null };
To enable the creation of this array, you can either declare its type explicitly or cast one of the elements as a nullable integer, as follows:
var nullables = new [] { (int?)1, 2, 3, null };
The same limitation applies when using inheritance hierarchies or objects of different classes that each implement a shared interface. For example, if we have an IPerson interface that is implemented by both the Employee and Contractor classes, the following array declaration is invalid:
var people = new []
{
new Employee("Bob"),
new Employee("Sam"),
new Contractor("Mel")
};
Again, you can either declare the array with an explicit type to remove this problem or cast one of the elements to the superclass or shared interface.
var people = new []
{
(IPerson)new Employee("Bob"),
new Employee("Sam"),
new Contractor("Mel")
};
25 October 2008