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 typeA, and at least one of them is directly of typeA(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: