As Rofus and Jeroin correctly pointed out in comments the conversion between T to T? is always implicit when you do the comparison with "Null
" 7 becomes a "Nullable<int>
"
bool bar = foo?.Count > 7;
is similar to -
int? count = null;
int? k = 7; // Implicit conversion here!
var bar = count > k;
For your second question on the >
operator. Yes, while the Nullable<T>
struct does not define operators such as <
, >
, or even ==
, still the following code compiles and executes correctly which is similar to your case -
int? x = 3;
int? y = 10;
bool b = x > y;
This is because compiler lifts
the greater than operator from underlying value type like -
bool b = (x.HasValue && y.HasValue) ? (x.Value > y.Value) : false;
Operator Lifting
or Lifted Operators
means you can implicitly use T's operators on T?. Compiler has different set of rules on different set of operators on handling them on Nullable<T>
types.