Home >Backend Development >C++ >Why Does My C# Ternary Operator Fail with Nullable Types: `GetBoolValue() ? 10 : null`?
C# Nullable Types and the Ternary Operator: Resolving Type Inconsistencies
In C#, using the ternary operator (? :
) with nullable types (like int?
) can lead to the error "Type of conditional expression cannot be determined...". This occurs when the true and false branches of the ternary operator have incompatible types. For example, GetBoolValue() ? 10 : null
fails because 10
is an int
and null
represents the absence of a value. The compiler can't decide on a single type for the expression.
The problem stems from the ternary operator's need for a consistent return type. While null
can be assigned to a nullable integer (int?
), a plain int
cannot implicitly become an int?
.
Here are several ways to correct this:
Explicit Cast to Nullable Integer: Cast the integer literal to int?
:
<code class="language-csharp">x = GetBoolValue() ? (int?)10 : null;</code>
Explicit Null Conversion: Explicitly cast null
to int?
:
<code class="language-csharp">x = GetBoolValue() ? 10 : (int?)null;</code>
Using the default
Keyword: The default
keyword provides a type-safe way to get the default value for a type, which is null
for nullable types:
<code class="language-csharp">x = GetBoolValue() ? 10 : default(int?);</code>
These solutions ensure type consistency, allowing the compiler to correctly infer the type of the ternary expression as int?
, thus resolving the compilation error. Choose the method that best suits your coding style and readability preferences.
The above is the detailed content of Why Does My C# Ternary Operator Fail with Nullable Types: `GetBoolValue() ? 10 : null`?. For more information, please follow other related articles on the PHP Chinese website!