C#中null==null编译报错咨询:与C#6教程描述不一致
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 istrue - If one operand is
nulland the other isn't, the result isnull(which acts asfalsein 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

