Prev | Current Page 236 | Next

Jon Skeet

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

Nullable. In addition,
the System.Nullable static class provides utility methods that occasionally make nullable
types easier to work with. (From now on I??™ll leave out the namespace, to make life
simpler.) We??™ll look at both of these types in turn, and for this section I??™ll avoid any extra
features provided by the language, so you??™ll be able to understand what??™s going on in
the IL code when we do look at the C# 2 syntactic sugar.
116 CHAPTER 4 Saying nothing with nullable types
4.2.1 Introducing Nullable
As you can tell by its name, Nullable is a generic type. The type parameter T has the
value type constraint on it. As I mentioned in section 3.3.1, this also means you can??™t
use another nullable type as the argument??”so Nullable> is forbidden,
for instance, even though Nullable is a value type in every other way. The type
of T for any particular nullable type is called the underlying type of that nullable type. For
example, the underlying type of Nullable is int.
The most important parts of Nullable are its properties, HasValue and
Value. They do the obvious thing: Value represents the non-nullable value (the
???real??? one, if you will) when there is one, and throws an InvalidOperation-
Exception if (conceptually) there is no real value. HasValue is simply a Boolean
property indicating whether there??™s a real value or whether the instance should be
regarded as null.


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