There is no difference between these two lines, because the compiler, in the second line, understands that it is an array of type int.
var x = new int[] { 1, 2, 3 }; //Fine, x is int[]
var x = new [] { 1, 2, 3 }; //Fine, x is int[]
But why can’t I do this with different types? Why doesn’t the compiler convert my variable to type object?
var x = new object[] { 1, "df", 5 }; //Fine, x is object[]
var x = new [] { 1, "df", 5 }; //Error! "No best type found for implicity-typed-array"
EDIT:
Thanks for all your answers. But I still wonder, what are the pros and cons to make all expressions that the compiler can’t convert to type object? (Because I use var notation which means that it can’t be any type. I understand like this.) Why doesn’t the compiler find the nearest type of the array members by going up the inheritance tree?
The
new []notation is for saving you to type an explicit type of the array members (or allowing you to create arrays where its elements have an anonymous type), but its type inference is limited in that all elements must share the same type or be implicitly convertible to a common type shared by at least one member. See C# Specification, section 7.6.10.4:Key point here is that the “best common type” can only be one of the types already present. As Damien_The_Unbeliever pointed out in a comment: “As Mr. Lippert is fond of pointing out around inference, whenever it’s looking for a best common type, it will only return one of the types that is already present – it doesn’t go hunting for the most-derived common ancestor.”.
Just because every array could be an
object []doesn’t mean it should. From a compiler perspective that’d be a trivial last-resort choice, but a very counter-intuitive one for the developer, I guess.