You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中null==null编译报错咨询:与C#6教程描述不一致

Why null == null Fails to Compile in C#

Great question—let's unpack why you're seeing a compilation error here, even though the C# 6 tutorial notes that lifted equality operators treat nulls the same as reference types (where two nulls are equal).

The Core Problem

The issue boils down to this: untyped null has no explicit type in C#. When you write null == null, the compiler has no clue what kind of null you're trying to compare. The == operator requires both operands to belong to a type that defines this operator, and without a concrete type (like a reference type or nullable value type), the compiler can't resolve which version of == to use. This leads to the error:

CS0019: Operator '==' cannot be applied to operands of type '' and ''

Why the Tutorial's Second Example Works

The tutorial's second line (bool?)null == (bool?)null compiles perfectly because you're explicitly casting those nulls to bool? (a nullable value type). Lifted equality operators are built specifically for nullable value types—they extend the base value type's equality logic to handle null cases:

  • If both operands are null, the result is true
  • If one operand is null and the other isn't, the result is null (which acts as false in a boolean context)
  • If neither is null, it uses the underlying value type's standard equality check

Fixing the null == null Line

To get the first line to compile and return true as expected, you just need to assign a type to the nulls. Here are a couple of valid approaches:

// Cast to object (a reference type)
Console.WriteLine((object)null == null); // Outputs True

// Use a nullable value type
Console.WriteLine((int?)null == null); // Outputs True

For reference types, two null references are always considered equal, which matches what the tutorial describes.

Quick Recap

The tutorial's note about lifted equality operators applies to typed nulls—either null references for reference types, or null values for nullable value types. Raw, untyped null can't be compared directly because the compiler can't figure out which equality operator to invoke.

内容的提问来源于stack exchange,提问作者Huibin Zhang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:41:17