Search code examples
c#nullnullable

Why does it make sense in C# to compare nullable and non-nullable int?


I've always used the coalescing operator (a.k.a. "really surprised operator, i.e. "??") to get rid of phony nullables (usually fetched from DB as allowing nulls but known to me never to be at that value). It looks like so.

int serious = GetSomeReallyNonNullValue();
int? phony = GetNullableButActuallyNonNullValue();
int result = serious + (phony ?? 0);

However, I just noticed that the below actually compiled. Can't see how it makes sense. And I can't see intuitively if null value will evaluate the expression to true or false...

int? test = null;
if (test < 1337) ;

Solution

  • A lot has been written about "lifting" operations in C# (eg. here), where operators with Nullable<T> arguments are treated as operators on T when all operands are non-null. And null is only equivalent to itself.

    usually fetched from DB as allowing nulls but known to me never to be at that value

    In which case why is the column not set to not null?

    The lifting is there because so many databases have nullable columns when they should not be.