Wednesday, December 21, 2011

Implicitly typed arrays in C# 3.0

In this post, I plan to talk about Implicitly typed arrays. In C# 3.0, as with Implicitly typed local variables, you can also create an array of objects that use type inference to determine what array type they are. So the following statements would create an array of ints and doubles respectively, based on the types of the elements specified within the curly brackets -

1//Examples of type inference
2var myIntegers = new[] { 1, 2, 3, 4, 5 };
3var myDoubles = new[] { 1, 2.1, 3.2, 4.3 };

Although the examples show primitive types as array elements, they are not limited to value types. The compiler will automatically infer the type based on the elements and assign it to the correct array type on the left hand side. The example below shows elements using a class Dog and its equivalent in C# 2.0

1var myPets = new[]
2 {
3 new Dog( "Spike" ),
4 new Dog( "Snoopy" )
5 };
7Dog[] pets = new Dog[2];
8pets[0] = new Dog("Spike");
9pets[0] = new Dog("Snoopy");

What you cannot do

For starters, you cannot mix and match types within your array. You also cannot have nulls when you have an array of value types. So, both the statements shown below are not legal -

1//Cannot mix types
2var mixedArray = new[] { 0, "one", 2, "three" };
3//Cannot have nulls, when you mix with value types
4var arrayWithNulls = new [] { 1, 2, null };

However, the following statement is acceptable, as it forces the compiler to create an array of nullable ints -

1var arrayWithNulls = new[] { (int?)1, 2, 3, null };

Inference when using types from the same inheritance tree

When you have elements in the array that have types from the same inference tree, at least one of the types in the list have will have to be base class. For example, if we have the inheritance as shown below -


then, the first statement will not work, while the second one will -

1var myPets = new[] { new Cat(), new Dog() } ;
2var myPets1 = new[] { new Cat(), new Pet() } ;

If you want to create an array of IAnimal elements, then at least one of the elements in the array will have to be explicitly typed to an IAnimal as shown below -

1IAnimal dog = new Dog();
2var myPets2 = new[] { dog, new Cat() };

You cannot call it Implicitly typed, then. Can you? :)

No comments: