c# – Why doesn't null work with the ternary operator?

Question:

Testing … The following statement does not compile because there is no implicit conversion between null .

CS0173 Cannot determine the type of the conditional expression because there is no implicit cast between '<NULL>' and '<NULL>'

string pp = true ? null : null;

Answer:

The ternary operator needs to determine the type of the conditional expression. This is done by following the following points that appear in the language specification :

If x has type X and y has type Y , then

  • If an implicit conversion (implicit conversions) exists from X to Y , but not from Y to X , then Y is the type of the conditional expression.

  • If an implicit conversion (implicit conversions) exists from Y to X , but not from X to Y , then X is the type of the conditional expression.

  • Otherwise, no expression type can be determined and a compile-time error occurs.

The problem is that null has no type, so since neither part of the expression can determine a type, the error occurs.

To solve it, you simply have to assign a type to either of the two expressions, for example:

string pp = true ? (string)null : null;
Scroll to Top