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.
As a slight addition to the Skeet's reply:
You can either cast one of the array items to the type you need (interface in this case) or if you had just a single element of that type (not deriving but of a direct type). Such as
this will work, but pls don't do that :) Just define the array type and change the
new[]
tonew IWindsorinstaller[]
. It's much more readable having the array type defined explicitly.Note: here UIViewController can be any class
If the instances can all be cast to the type of any one instance, than that type will be used. It's not enough for all instances to have any type in common, or else the implicity array initialization would always succeed and often generate undesired
new object[]
arrays.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
,obj2
andobj3
as 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: