Search code examples
c#.net-3.5interfaceinline-if

inline if and interfaces (polymorphism)


public class Foo : IFooBarable {...}
public class Bar : IFooBarable {...}

So why then will this not compile...

int a = 1;
IFooBarable ting = a == 1 ? new Foo() : new Bar();

but this will...

IFooBarable ting = a == 1 ? new Foo() : new Foo();
IFooBarable ting = a == 1 ? new Bar() : new Bar();

Solution

  • The compiler first tries to evaluate the right-hand expression:

    ? new Foo() : new Bar();
    

    There's no implicit conversion between those two hence the error message. You can do this:

    IFooBarable ting = a == 1 ? (IFooBarable)(new Foo()) : (IFooBarable)(new Bar());