Question

Why can't the c# compiler infer the type of the conditional expression in the code below?

class A {}
class B : A {}
class C : A {}

A TestInference ()
{
    return new Random ().Next () == 0 ? new B () : new C ();
}

EDIT: I know how to fix the compiler error (just cast the B or the C to A), my question is: why can't the compiler understand that the type is A by itself?

Était-ce utile?

La solution

From the docs:

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

In your case there is no implicit conversion, but if you would cast one of them to A it should work.

But yeah, one could argue that it should be able to figure it out itself, but there are actually some good reasons for it not doing that, as explained in the first of the links Steve posted.

Consider the following case:

interface D {}
class A {}
class B : A, D {}
class C : A, D {}

var x = condition ? new B() : new C();

Should the compiler make x an A, or a D?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top