I was under the impression that the C# compiler will implicitly type an array based off a type that they can all be implicitly converted to.
The compiler generates
No best type found for implicitly-typed array
public interface ISomething {}
public interface ISomething2 {}
public interface ISomething3 {}
public class Foo : ISomething { }
public class Bar : ISomething, ISomething2 { }
public class Car : ISomething, ISomething3 { }
void Main()
{
var obj1 = new Foo();
var obj2 = new Bar();
var obj3 = new Car();
var objects= new [] { obj1, obj2, obj3 };
}
I know that the way to correct this is to declare the type like:
new ISomething [] { obj1, ...}
But I’m after an under the covers type help here.
The C# compiler considers the set of types of all the specified elements. It does not consider common base types etc.
You could cast one of the expressions:
… but personally I’d just use the explicit form:
Alternatively, if you explicitly declared any or all of
obj1,obj2andobj3as typeISomething, that would work fine too without changing the array initialization expression.From the C# 3 spec, section 7.5.10.4:
Section 7.4.2.13 looks like this: