If we??™d tried unboxing
the last value of boxed to a non-nullable int, the program would have blown up with a
NullReferenceException.
Now that we understand the behavior of boxing and unboxing, we can begin to
tackle the behavior of Nullable
.Equals.
4.2.3 Equality of Nullable instances
Nullable overrides object.Equals(object) but doesn??™t introduce any equality
operators or provide an Equals(Nullable) method. Since the framework has supplied
the basic building blocks, languages can add extra functionality on top, including
making existing operators work as we??™d expect them to. We??™ll see the details of
that in section 4.3.3, but the basic equality as defined by the vanilla Equals method
follows these rules for a call to first.Equals(second):
?– If first has no value and second is null, they are equal.
?– If first has no value and second isn??™t null, they aren??™t equal.
?– If first has a value and second is null, they aren??™t equal.
?– Otherwise, they??™re equal if first??™s value is equal to second.
Note that we don??™t have to consider the case where second is another Nullable
because the rules of boxing prohibit that situation. The type of second is object, so in
order to be a Nullable it would have to be boxed, and as we have just seen, boxing
a nullable instance creates a box of the non-nullable type or returns a null reference.
Pages:
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254