In fact, the behavior was only changed shortly before the
release of .NET 2.0, as the result of community requests.
An instance of Nullable
is boxed to either a null reference (if it doesn??™t have a
value) or a boxed value of T (if it does). You can unbox from a boxed value either to
its normal type or to the corresponding nullable type. Unboxing a null reference will
throw a NullReferenceException if you unbox to the normal type, but will unbox to
an instance without a value if you unbox to the appropriate nullable type. This behavior
is shown in listing 4.2.
Nullable nullable = 5;
object boxed = nullable;
Console.WriteLine(boxed.GetType());
int normal = (int)boxed;
Console.WriteLine(normal);
nullable = (Nullable)boxed;
Console.WriteLine(nullable);
Listing 4.2 Boxing and unboxing behavior of nullable types
Boxes a nullable
with value
Unboxes to nonnullable
variable
Unboxes to
nullable variable
119 System.Nullable and System.Nullable
nullable = new Nullable();
boxed = nullable;
Console.WriteLine (boxed==null);
nullable = (Nullable)boxed;
Console.WriteLine(nullable.HasValue);
The output of listing 4.2 shows that the type of the boxed value is printed as System.
Int32 (not System.Nullable). It then confirms that we can retrieve
the value by unboxing to either just int or to Nullable. Finally, the output demonstrates
we can box from a nullable instance without a value to a null reference and
successfully unbox again to another value-less nullable instance.
Pages:
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253