#596 – Implicitly-Typed Arrays and Best Type Inference
June 1, 2012 Leave a comment
When you declare and initialize an implicitly-typed array, the C# compiler tries to find a single type that best fits all of the values that you provide. Constant values can be of different types, as long as they are all implicitly convertible to a single common type.
// Becomes int[] var numbers = new[] { 1, 2, 3 }; // Becomes double[] var moreNums = new[] { 1.1, 2.2, 3.3 }; // Also double[], int values convertible to double var evenMore = new[] { 1, 2, 3.3 };
Note that the compiler will not implicitly convert everything to object, if System.Object is the only common type found.
// Compile-time error: No best type found for implicitly-typed array var stuff = new[] { 1, 2, "dog" };
If you did want an array of objects, you could use an explicit cast.
// Becomes object[] var stuffFixed = new[] { (object)1, (object)2, (object)"dog" };