Wednesday 15 April 2015

C# How To: Using Implicitly Typed Arrays

Implicitly typed arrays allow the C# compiler to determine the most appropriate type for an array. The selected type is based on the values you initialise the array with. This useful feature was introduced in C# 3.0.
var intArray = new [] { 1, 2, 3 };
var stringArray  = new [] { "hello""world"null };
var nullableIntArray = new [] { 1, (int?)2, 3 };

Console.WriteLine(intArray.GetType());
Console.WriteLine(stringArray.GetType());
Console.WriteLine(nullableIntArray.GetType());

// Following results in a compile-time error:
//    "No best type found for implicitly-typed array"
var notGoingToWorkArray = new [] { "hello", 1, 2f };