Why can I check DateTime for null, even though it is a value type?
This compiles without error or warning, how is this possible?
i开发者_StackOverflow社区f (DateTime.Now == null) { }
EDIT:
It's getting even better:
If I do the same with Decimal
, int
or a user defined struct
, I get a compiler error.
What is the difference?
Why can TimeSpan and Guid Structs be compared to null?
Good explanation in the answer here
Several code-analysis tools (like Resharper) will flag it as "always false" and subsequent code as unreachable.
If you put code in the block, it used to warn of unreachable code, but IIRC this warning disappeared (the issue has been reported).
As for "why"; because there is a legal implicit conversion (box or nullable) that allows the test to work as per the language requirements. However, it will always be false
, and IIRC the compiler is smart enough to excise the clearly unreachable code (shame about the warning).
You can compare any value type to null. However, it will always be false because a value type can never be null.
As to why it's allowed, ALL types in .NET (including those that inherit more directly from System.ValueType) inherit from System.Object, which defines an == operator. That means that every type can be compared for referential equality. However, ValueTypes will never evaluate to null because the CLR always ensures, at very deep levels, that ValueType "references" always have a value even when boxed as reference types.
精彩评论