If var
keyword is resolved at compile time, how does the following work?
class A {
}
class B : A {
}
int k = 1;
var x = (k < 0) ? new B() : new A();
Edit:
I finally understood that the problem is not about the var
itself, but about the behaviour of the ?:
operator. For some reason, I thought that the following could be possible:
object x = something ? 1 : ""
and that's not possible at all :)
Related question (about ternary operator):
Why assigning null in ternary operator fails: no implicit conversion between null and int?
The result is of type A
, because both of the variables are of type A
, and at least one of them is directly of type A
(not through some conversion).
The compiler takes a look at both parts of the ternary expression, and if one of them is a subtype of the other, the entire expression becomes the more general supertype.
However, if neither is directly of the common type, then a compiler error occurs, probably because it doesn't know how much to upcast for you (and it doesn't feel like finding out).
See here:
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.
condition ? first_expression : second_expression;
[...]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With