Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doubts about the 'var' keyword and ternary operator ?:

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?

like image 878
Oscar Mederos Avatar asked Feb 23 '23 19:02

Oscar Mederos


1 Answers

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.

like image 119
user541686 Avatar answered Mar 06 '23 23:03

user541686