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 -
2 | var myIntegers = new [] { 1, 2, 3, 4, 5 }; |
3 | var 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
7 | Dog[] pets = new Dog[2]; |
8 | pets[0] = new Dog( "Spike" ); |
9 | pets[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 -
2 | var mixedArray = new [] { 0, "one" , 2, "three" }; |
4 | var arrayWithNulls = new [] { 1, 2, null }; |
However, the following statement is acceptable, as it forces the compiler to create an array of nullable ints -
1 | var 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 -
1 | var myPets = new [] { new Cat(), new Dog() } ; |
2 | var 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 -
1 | IAnimal dog = new Dog(); |
2 | var myPets2 = new [] { dog, new Cat() }; |
You cannot call it Implicitly typed, then. Can you?
No comments:
Post a Comment