Prev | Current Page 240 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

1 Using various members of Nullable
118 CHAPTER 4 Saying nothing with nullable types
instance. Next, we create an instance that doesn??™t have a value, and use the same members
in the same order, just omitting the Value property and the explicit conversion to
int since these would throw exceptions. The output of listing 4.1 is as follows:
Instance with value:
HasValue: True
Value: 5
Explicit conversion: 5
GetValueOrDefault(): 5
GetValueOrDefault(10): 5
ToString(): "5"
GetHashCode(): 5
Instance without value:
HasValue: False
GetValueOrDefault(): 0
GetValueOrDefault(10): 10
ToString(): ""
GetHashCode(): 0
So far, you could probably have predicted all of the results just by looking at the members
provided by Nullable. When it comes to boxing and unboxing, however,
there??™s special behavior to make nullable types behave how we??™d really like them to
behave, rather than how they??™d behave if we slavishly followed the normal boxing rules.
4.2.2 Boxing and unboxing
It??™s important to remember that Nullable is a struct??”a value type. This means that
if you want to convert it to a reference type (object is the most obvious example), you??™ll
need to box it. It is only with respect to boxing and unboxing that the CLR itself has any
special behavior regarding nullable types??”the rest is ???standard??? generics, conversions,
method calls, and so forth.


Pages:
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252