Prev | Current Page 248 | Next

Jon Skeet

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

We want to
give the same sort of feeling that using null does with reference types. If it seems odd
to you that I??™ve talked about feelings in both this section and the last one, just think
about who writes code, and who reads it. Sure, the compiler has to understand the
code, and it couldn??™t care less about the subtle nuances of style??”but very few pieces
of code used in production systems are written and then never read again. Anything
you can do to get the reader into the mental process you were going through when
you originally wrote the code is good??”and using the familiar null literal helps to
achieve that.
With that in mind, we??™re going to change the example we??™re using from one that
just shows syntax and behavior to one that gives an impression of how nullable types
might be used. We??™ll consider modeling a Person class where you need to know the
name, date of birth, and date of death of a person. We??™ll only keep track of people
who have definitely been born, but some of those people may still be alive??”in which
case our date of death is represented by null. Listing 4.4 shows some of the possible
code. Although a real class would clearly have more operations available, we??™re just
looking at the calculation of age for this example.
class Person
{
DateTime birth;
DateTime? death;
string name;
public TimeSpan Age
{
get
{
if (death==null)
{
return DateTime.


Pages:
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260