Home >Backend Development >C++ >Why is `GetBoolValue() ? 10 : null` Forbidden in a C# Ternary Operator?
C# Ternary Operator and Nullable Integers: Why ? 10 : null
Fails
The C# ternary operator (condition ? value1 : value2
) requires that both value1
and value2
have compatible types. Let's examine why the following code produces a compiler error:
<code class="language-csharp">int? x = GetBoolValue() ? 10 : null; </code>
The error message, "Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '10
as an int
and null
as, well, null
(which in this context represents the absence of a value). Since there's no automatic conversion between an int
and a null value, the compiler can't infer the resulting type of the ternary expression.
Solutions:
To fix this, we must ensure type consistency. Here are several approaches:
Explicitly Cast 10 to a Nullable Integer (int?
):
<code class="language-csharp">int? x = GetBoolValue() ? (int?)10 : null;</code>
This explicitly tells the compiler that 10
should be treated as a nullable integer, allowing the null
to be a valid second branch.
Explicitly Cast null
to a Nullable Integer:
<code class="language-csharp">int? x = GetBoolValue() ? 10 : (int?)null;</code>
This explicitly casts null
to int?
, making both sides of the ternary operator compatible.
Use the Default Value for int?
:
<code class="language-csharp">int? x = GetBoolValue() ? 10 : default(int?);</code>
default(int?)
evaluates to null
, providing a type-safe way to represent the null case. This is often preferred for clarity.
All three solutions achieve the same result: x
will be assigned either 10
(as an int?
) or null
based on the result of GetBoolValue()
. The key is to ensure both branches of the ternary operator have the same, compatible type. Using the default
keyword is generally considered the most readable and maintainable solution.
The above is the detailed content of Why is `GetBoolValue() ? 10 : null` Forbidden in a C# Ternary Operator?. For more information, please follow other related articles on the PHP Chinese website!