There was a huge debate about this oddity when the feature was originally designed back in C# 2.0. The problem is that C# users are completely used to this being meaningful:
if(someReference == null)
When extending equality to nullable value types, you have the following choices.
Nullable equality is truly lifted. If one or both of the operands is null then the result is neither true, nor false, but null. In this case you can either:
a) Make it illegal to have a nullable value type equality in an if
statement, because the if
statement needs a bool, not a nullable bool. Instead, require everyone to use HasValue
if they want to compare to null. This is verbose and irritating.
b) Automatically convert null to false. The downside of this is that x==null
returns false if x is null, which is confusing and works against people's understanding of null comparisons with reference types.
Nullable equality is not lifted. Nullable equality is either true or false, and comparison to null is a null check. This makes nullable equality inconsistent with nullable inequality.
None of these choices is obviously correct; they all have pros and cons. VBScript chooses 1b, for example. After much debate the C# design team chose #2.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…