Given the following C# code:
var a = new[] {"123", "321", 1}; //no best type found for implicitly typed array
And its counterpart in VB.NET:
Dim a = {"123", "321", 1} 'no errors
It appears that VB.NET is able to correctly infer type of a
= Object()
, while C# complains until the above is fixed to:
var a = new object[] {"123", "321", 1};
Is there a way to auto-infer type in C# for the above scenario?
EDIT: Interesting observation after playing with different types in a C# sandbox - type is correctly inferred if all elements have common parent in the inheritance tree, and that parent is not an Object
, or if elements can be cast into a wider type (without loss of precision, for example Integer -> Double
). So both of these would work:
var a = new[] {1, 1.0}; //will infer double[]
var a = new[] {new A(), new B()}; //will infer A[], if B inherits from A
I think this behavior is inconsistent in C#, because all types inherit from Object
, so it's not a much different ancestor than any other type. This is probably a by-design, so no point to argue, but if you know the reason, would be interesting to know why.