One aspect of lifted operators and nullable conversion that has caused some confusion
is unintended comparisons with null when using a non-nullable value type.
The code that follows is legal, but not useful:
int i = 5;
if (i == null)
{
Console.WriteLine ("Never going to happen");
}
The C# compiler raises warnings on this code, but you may consider it surprising that
it??™s allowed at all. What??™s happening is that the compiler sees the int expression on the
left side of the ==, sees null on the right side, and knows that there??™s an implicit conversion
to int? from each of them. Because a comparison between two int? values is
perfectly valid, the code doesn??™t generate an error??”just the warning. As a further complication,
this isn??™t allowed in the case where instead of int, we??™re dealing with a
generic type parameter that has been constrained to be a value type??”the rules on
generics prohibit the comparison with null in that situation.
Either way, there??™ll be either an error or a warning, so as long as you look closely at
warnings, you shouldn??™t end up with deficient code due to this quirk??”and hopefully
pointing it out to you now may save you from getting a headache trying to work out
exactly what??™s going on.
Table 4.1 Examples of lifted operators applied to nullable integers
Expression Lifted operator Result
-nullInt int? ??“(int? x) null
-five int? ??“(int? x) -5
five + nullInt int? +(int? x, int? y) null
five + five int? +(int? x, int? y) 10
nullInt == nullInt bool ==(int? x, int? y) true
five == five bool ==(int? x, int? y) true
five == nullInt bool ==(int? x, int? y) false
five == four bool ==(int? x, int? y) false
four < five bool <(int? x, int? y) true
nullInt < five bool <(int? x, int? y) false
five < nullInt bool <(int? x, int? y) false
nullInt < nullInt bool <(int? x, int? y) false
nullInt <= nullInt bool <=(int? x, int? y) false
127 C# 2??™s syntactic sugar for nullable types
Now we??™re able to answer the question at the end of the previous section??”why we
used death.
Pages:
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267