0

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) ;
Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

1 Answers1

1

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.

Richard
  • 106,783
  • 21
  • 203
  • 265
  • Great answer. +1 for that. As for your question why DB's allowing *null* - well, because people are sloppy doing the preparations, lazy doing maintenance and stupid doing code reviews. And just to be clear - on occasion, I'm those people. Not this time, though. :) – Konrad Viltersten Sep 25 '15 at 12:38
  • This answer, and the linked article, both talk about operations on two nullable values. That doesn't explain why its valid to operate on a nullable with a *non-nullable*. (Presumably the answer is that the non-nullable is treated as if it were a nullable that had a value...) – ToolmakerSteve Jan 27 '19 at 22:59