Home >Backend Development >C++ >Why Does the Ternary Operator Fail with Nullable Types in C#?
The ternary computing symbols and empty types in the c#: limit details
When processing the empty value type, the ternary computing symbol (? :) may have unexpected behaviors. A common problem is to try to use the ternary computing symbol to assign a integer character or NULL to the canal integer variable.
For example, consider the following code:
In this code, the ternary computing symbol attempts to calculate the right expression:
<code class="language-csharp">int? x = GetBoolValue() ? 10 : null;</code>
Among them, Return to a Boolean value, 10 is a integer literal, null is a vacant reference. The compiler attempts to convert these values to match the type of the left expression, that is,
<code class="language-csharp">GetBoolValue() ? 10 : null</code>.
GetBoolValue()
However, there is no hidden conversion between the literal volume (cannot be empty) and the empty integer (int?
). Similarly, there is no hidden conversion between NULL and integer. This causes the compiler error:
int?
In order to solve this problem, the right expression must be modified to ensure that the two branches of the three -yuan operator return the values compatible with the left expression. This can be achieved through implicit conversion or explicit conversion:
<code>无法确定条件表达式的类型,因为整型和<null>之间没有隐式转换。</code>
Through these modifications, the compiler can successfully calculate the right expression and determine the type of conditional expression to eliminate errors.
The above is the detailed content of Why Does the Ternary Operator Fail with Nullable Types in C#?. For more information, please follow other related articles on the PHP Chinese website!