Now-birth;
}
else
{
return death.Value-birth;
Listing 4.4 Part of a Person class including calculation of age
Checks
HasValue
B
Unwraps for
calculation
C
123 C# 2??™s syntactic sugar for nullable types
}
}
}
public Person(string name,
DateTime birth,
DateTime? death)
{
this.birth = birth;
this.death = death;
this.name = name;
}
}
...
Person turing = new Person("Alan Turing",
new DateTime(1912, 6, 23),
new DateTime(1954, 6, 7));
Person knuth = new Person("Donald Knuth",
new DateTime(1938, 1, 10),
null);
Listing 4.4 doesn??™t produce any output, but the very fact that it compiles might have
surprised you before reading this chapter. Apart from the use of the ? modifier causing
confusion, you might have found it very odd that you could compare a DateTime?
with null, or pass null as the argument for a DateTime? parameter.
Hopefully by now the meaning is intuitive??”when we compare the death variable
with null, we??™re asking whether its value is the null value or not. Likewise when we use
null as a DateTime? instance, we??™re really creating the null value for the type by calling
the default constructor. Indeed, you can see in the generated IL that the code the
compiler spits out for listing 4.4 really does just call the death.HasValue property B,
and creates a new instance of DateTime? E using the default constructor (represented
in IL as the initobj instruction).
Pages:
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261