Home >Backend Development >C++ >Why Does '? 10 : null' Fail with Nullable Types in C#?
The three yuan computing symbols and the empty type: solve the mystery of "? 10: null"
Consider the following code fragment:
<code class="language-c#">int? x = GetBoolValue() ? 10 : null;</code>The goal here is: if
returns GetBoolValue()
, the value 10 is assigned to the empty integer true
; otherwise, x
is kept x
. However, the compiler will mark an error: null
<code>错误:无法确定条件表达式的类型,因为在 int 和 <null> 之间没有隐式转换。</code>Question interpretation
This error highlights the problem of non -matching types in the three -yuan expression. The left expression Returns a
value, and the parsing is or GetBoolValue()
. The right expression attempts to combine two expressions: bool
true
false
, this is a
10
, this is an empty word. int
int?
null
, they are incompatible. Solving the type does not match int
10
null
In order to solve this problem, the right expression needs to be compatible with the type of empty types. There are several ways:
int
null
:
int?
<code class="language-c#"> x = GetBoolValue() ? (int?)10 : null;</code>
to
<code class="language-c#"> x = GetBoolValue() ? 10 : (int?)null; x = GetBoolValue() ? 10 : default(int?);</code>:
.
to:
Non -emptyint?
null
By compatible with the type of the right expression, you can solve the problem that the type does not match the problem and distribute the appropriate value according to the return value. int?
The above is the detailed content of Why Does '? 10 : null' Fail with Nullable Types in C#?. For more information, please follow other related articles on the PHP Chinese website!