Prev | Current Page 238 | Next

Jon Skeet

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

Very few value types in the framework are mutable, fortunately.
Nullable introduces a single new method, GetValueOrDefault, which has two
overloads. Both return the value of the instance if there is one, or a default value otherwise.
One overload doesn??™t have any parameters (in which case the generic default
value of the underlying type is used), and the other allows you to specify the default
value to return if necessary.
The other methods implemented by Nullable all override existing methods:
GetHashCode, ToString, and Equals. GetHashCode returns 0 if the instance doesn??™t
have a value, or the result of calling GetHashCode on the value if there is one.
ToString returns an empty string if there isn??™t a value, or the result of calling
117 System.Nullable and System.Nullable
ToString on the value if there is. Equals is slightly more complicated??”we??™ll come
back to it when we??™ve discussed boxing.
Finally, two conversions are provided by the framework. First, there is an implicit
conversion from T to Nullable. This always results in an instance where HasValue
returns true. Likewise, there is an explicit operator converting from Nullable to
T, which behaves exactly the same as the Value property, including throwing an exception
when there is no real value to return.
NOTE Wrapping and unwrapping??”The C# specification names the process of
converting an instance of T to an instance of Nullable wrapping, with
the obvious opposite process being called unwrapping.


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