Home > Backend Development > C++ > Why is `? 10 : null` Forbidden in C# Ternary Operators with Nullable Types?

Why is `? 10 : null` Forbidden in C# Ternary Operators with Nullable Types?

Mary-Kate Olsen
Release: 2025-01-28 21:51:10
Original
133 people have browsed it

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.

Consider the following code fragment:

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

or, we can use the default keyword:

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

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!

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