A lot of us are all too familiar with accidental episodes of the CS0173
compiler error, which is a type conversion error:
Type of conditional expression cannot be determined because there is no implicit conversion between 'class1' and 'class2'
Today, I made an assumption was that I could use the conditional operator ?:
within string interpolation, and it wouldn't care about the type used for the consequent or alternative. In my case, I wanted to check a long
to determine if it's value was less than zero, and if it was, display a string
saying Not Available
, and if it was not, then simply display the value of the long:
long x = 5;
string example = $"{(x < 0 ? "Not Available" : x)}";
This resulted in compiler error CS0173
due to the consequent being of type string
and the alternative being of type long
. It's a simple fix by using .ToString()
:
long x = 5;
string example = $"{(x < 0 ? "Not Available" : x.ToString())}";
But now I'm curious...
Why would the conditional operator ?:
even care about the type when utilized inside of string interpolation since the whole point is to display the string representation anyways?
Operators don't know the context they're being used. Either cases x+1
or y=x+1
the +
operator only knows that it is taking two arguments and returning the result. To illustrate, it's like
T Sum<T>(T numA, T numB){
//Do stuff
}
The same happens to ?:
, it's a method that takes three arguments and return the result. The result is strong typed, inferred from the inputs. Only then the result will be passed to the interpolation, which never happens in your case, since the ternary operator will give the compile time error, since it cannot implicit convert long
to string
.
Edit: Now that is possible with C# 9, as @RandRandom pointed out in the comments, as they changed the implementation of the ternary operator.