Home >Backend Development >C++ >Why Does '? 10 : null' Fail with Nullable Types in C#?

Why Does '? 10 : null' Fail with Nullable Types in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-28 22:10:10946browse

Why Does

The three yuan computing symbols and the empty type: solve the mystery of "? 10: null"

When dealing with empty types, understanding that they are compatible with other data types in expression. A common scenario can cause accidental errors, that is, the three -yuan computing symbol is used together with the empty type and non -empty type.

Consider the following code fragment:

<code class="language-c#">int? x = GetBoolValue() ? 10 : null;</code>
The goal here is: if

returns GetBoolValue(), the value 10 is assigned to the empty integer true; otherwise, x is kept x. However, the compiler will mark an error: null

<code>错误:无法确定条件表达式的类型,因为在 int 和 <null> 之间没有隐式转换。</code>
Question interpretation

This error highlights the problem of non -matching types in the three -yuan expression. The left expression Returns a

value, and the parsing is

or GetBoolValue(). The right expression attempts to combine two expressions: bool true false , this is a

literal volume (not
    ).
  • 10 , this is an empty word. int int?
  • The compiler first tries to evaluate the right expression. It encounters literal
  • and empty characters null, they are incompatible.
  • and do not define hidden conversion, resulting in incomplete types of types.

Solving the type does not match int 10 null In order to solve this problem, the right expression needs to be compatible with the type of empty types. There are several ways: int null

Converted the literally to

:

    Use the empty type or default value:
  • int?

    implicit conversion
    <code class="language-c#">  x = GetBoolValue() ? (int?)10 : null;</code>
  • The hidden conversion mentioned in the acceptable answer is:

    to
    <code class="language-c#">  x = GetBoolValue() ? 10 : (int?)null;
      x = GetBoolValue() ? 10 : default(int?);</code>
    :
  • The empty type
can be implicitly converted to

.

to

:

Non -empty
    can be converted to empty
  • . int? null By compatible with the type of the right expression, you can solve the problem that the type does not match the problem and distribute the appropriate value according to the return value. int?

The above is the detailed content of Why Does '? 10 : null' Fail with Nullable Types in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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