The C# specification
actually defines these terms with reference to the constructor taking
a parameter and the Value property, respectively. Indeed these calls are
generated by the C# code, even when it otherwise looks as if you??™re using
the conversions provided by the framework. The results are the same
either way, however. For the rest of this chapter, I won??™t distinguish
between the two implementations available.
Before we go any further, let??™s see all this in action. Listing 4.1 shows everything you
can do with Nullable
directly, leaving Equals aside for the moment.
static void Display(Nullable x)
{
Console.WriteLine ("HasValue: {0}", x.HasValue);
if (x.HasValue)
{
Console.WriteLine ("Value: {0}", x.Value);
Console.WriteLine ("Explicit conversion: {0}", (int)x);
}
Console.WriteLine ("GetValueOrDefault(): {0}",
x.GetValueOrDefault());
Console.WriteLine ("GetValueOrDefault(10): {0}",
x.GetValueOrDefault(10));
Console.WriteLine ("ToString(): \"{0}\"", x.ToString());
Console.WriteLine ("GetHashCode(): {0}", x.GetHashCode());
Console.WriteLine ();
}
...
Nullable x = 5;
x = new Nullable(5);
Console.WriteLine("Instance with value:");
Display(x);
x = new Nullable();
Console.WriteLine("Instance without value:");
Display(x);
In listing 4.1 we first show the two different ways (in terms of C# source code) of wrapping
a value of the underlying type, and then we use various different members on the
Listing 4.
Pages:
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251