Because the types in the array aren't specific object
- they are 3 different types that are all subclasses of object.
If you use a specific type that can be inferred in your array, the compiler will infer the type. For example, this is fine:
var arr = new[] {3, 4, 5}; // Will correctly infer int[]
Note that this is explicitly called out in 8.5.1 of the C# language spec, which states that for var
is subject to the following restrictions:
- The local-variable-declaration cannot include multiple local-variable-declarators.
- The local-variable-declarator must include a local-variable-initializer.
- The local-variable-initializer must be an expression.
- The initializer expression must have a compile-time type.
- The initializer expression cannot refer to the declared variable itself
In the case of arrays, there is an example specified:
var y = {1, 2, 3}; // Error, array initializer not permitted
As for the new [] {"bla bla bla..", 23, true };
example, this is called out in 7.6.10. There, this example:
var d = new[] { 1, "one", 2, "two" }; // Error
Is said to be an error because:
The last expression causes a compile-time error because neither int nor string is implicitly convertible to the other, and so there is no best common type. An explicitly typed array creation expression must be used in this case, for example specifying the type to be object[]. Alternatively, one of the elements can be cast to a common base type, which would then become the inferred element type