Does anyone have concrete information on how C# handles comparisons with Nullable<T>
types when one side of the comparison is null?
As I understand from experimenting with the compiler, it seems that the comparison always returns false, but I can't find any documentation to back that up. Is this a real feature of the language (and thus something I can count on), or is this an implementation detail that might change in future versions?
In other words, does the following method returning true imply y.HasValue
, and can you point me to some documentation that proves that it does?
public bool foo(int x, int? y) { return x < y; }
To handle NULLs correctly, SQL provides two special comparison operators: IS NULL and IS NOT NULL. They return only true or false and are the best practice for incorporating NULL values into your queries.
For comparison operators in SQL, NULL can be compared usingIS or IS NOT operator. SQL treats each NULL as a distinct value, so =,<,> can not beused for comparison.In general, NULL values are discarded when aggregate functions are applied to aparticular column.
ISNULL() can be used instead of = to test whether a value is NULL . (Comparing a value to NULL using = always yields NULL .) The ISNULL() function shares some special behaviors with the IS NULL comparison operator.
SQL has the is [not] null predicate to test if a particular value is null . With is [not] distinct from SQL also provides a comparison operator that treats two null values as the same. Note that you have to use the negated form with not to arrive at similar logic to the equals ( = ) operator.
Does anyone have concrete information on how C# handles comparisons with Nullable types when one side of the comparison is null?
Yes - the C# language specification, section 7.3.7. In this case, it's a relational operator:
For the relation operators
< > <= >=
a lifted form of an operator exists if the operand types are both non-nullable types and if the result type isbool
. The lifted form is constructed by adding a single?
modifier to each operand type. The lifted operator produces the valuefalse
if one or both operands are null. Otherwise, the lifted operator unwraps the operands and applies the underlying operator to produce thebool
result.
There are similarly detailed sections for other operators.
When in doubt about how some aspect of the language works (and whether it's guaranteed or implementation-specific), the C# language specification should be your first port of call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With