Prev | Current Page 260 | Next

Jon Skeet

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


I say ???roughly speaking??? because the formal rules in the specification involve lots of situations
where there are conversions involved between the types of first and second.
As ever, these aren??™t important in most uses of the operator, and I don??™t intend to go
through them??”consult the specification if you need the details.
Importantly, if the type of the second operand is the underlying type of the first
operand (and therefore non-nullable), then the overall result is that underlying type.
Let??™s take a look at a practical use for this by revisiting the Age property of listing 4.4.
As a reminder, here??™s how it was implemented back then, along with the relevant variable
declarations:
DateTime birth;
DateTime? death;
public TimeSpan Age
{
get
{
if (death==null)
{
return DateTime.Now-birth;
}
else
{
return death.Value-birth;
}
}
}
Note how both branches of the if statement subtract the value of birth from some nonnull
DateTime value. The value we??™re interested in is the latest time the person was
alive??”the time of the person??™s death if he or she has already died, or now otherwise. To
make progress in little steps, let??™s try just using the normal conditional operator first:
DateTime lastAlive = (death==null ? DateTime.Now : death.Value);
return lastAlive??“birth;
That??™s progress of a sort, but arguably the conditional operator has actually made it
harder to read rather than easier, even though the new code is shorter.


Pages:
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272