Home >Backend Development >C++ >Why is `? 10 : null` Forbidden in C# Ternary Operators with Nullable Types?
C#ternary computing and empty type: Why
report an error?
? 10 : null
When using the available type in C#, the type consistency in the expression is very important. The ternary computing character (? :) Evaluate the two expressions based on the condition. If the condition is true, the result of the first expression is returned, otherwise the result of the second expression will be returned.
Here, we try to assign int and null to the Cable int variable X. This can cause compilers errors, because there are no hidden conversion between these two types.
<code class="language-csharp">int? x = GetBoolValue() ? 10 : null; // 错误</code>The compiler first tries to evaluate the right expression:
The literal 10 is an INT type, and NULL is an empty type. There is no hidden conversion between the two, so errors occur.
<code class="language-csharp">GetBoolValue() ? 10 : null</code>In order to solve this problem, we can perform an explicit conversion to ensure the type consistency:
or, we can convert the empty word surface to int?:
<code class="language-csharp">int? x = GetBoolValue() ? (int?)10 : null; // 将10转换为int?</code>
or, we can use the default keyword:
<code class="language-csharp">int? x = GetBoolValue() ? 10 : (int?)null; // 将null转换为int?</code>
By ensuring the consistency of the type, we can avoid the compiler error and maintain the completeness of the type.
The above is the detailed content of Why is `? 10 : null` Forbidden in C# Ternary Operators with Nullable Types?. For more information, please follow other related articles on the PHP Chinese website!