Home > Backend Development > C++ > Why is `GetBoolValue() ? 10 : null` Forbidden in a C# Ternary Operator?

Why is `GetBoolValue() ? 10 : null` Forbidden in a C# Ternary Operator?

Susan Sarandon
Release: 2025-01-28 22:07:16
Original
827 people have browsed it

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>
Copy after login

The error message, "Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and ''", highlights the core problem. The compiler interprets 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:

  1. Explicitly Cast 10 to a Nullable Integer (int?):

    <code class="language-csharp">int? x = GetBoolValue() ? (int?)10 : null;</code>
    Copy after login

    This explicitly tells the compiler that 10 should be treated as a nullable integer, allowing the null to be a valid second branch.

  2. Explicitly Cast null to a Nullable Integer:

    <code class="language-csharp">int? x = GetBoolValue() ? 10 : (int?)null;</code>
    Copy after login

    This explicitly casts null to int?, making both sides of the ternary operator compatible.

  3. Use the Default Value for int?:

    <code class="language-csharp">int? x = GetBoolValue() ? 10 : default(int?);</code>
    Copy after login

    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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template