Prev | Current Page 261 | Next

Jon Skeet

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

The conditional
operator is often like that??”how much you use it is a matter of personal preference,
although it??™s worth consulting the rest of your team before using it extensively. Let??™s see
how the null coalescing operator improves things. We want to use the value of death if
it??™s non-null, and DateTime.Now otherwise. We can change the implementation to
DateTime lastAlive = death ?? DateTime.Now;
return lastAlive??“birth;
130 CHAPTER 4 Saying nothing with nullable types
Note how the type of the result is DateTime rather than DateTime? because we??™ve
used DateTime.Now as the second operand. We could shorten the whole thing to one
expression:
return (death ?? DateTime.Now)-birth;
However, this is a bit more obscure??”in particular, in the two-line version the name of
the lastAlive variable helps the reader to see why we??™re applying the null coalescing
operator. I hope you agree that the two-line version is simpler and more readable than
either the original version using the if statement or the version using the normal conditional
operator from C# 1. Of course, it relies on the reader understanding what the
null coalescing operator does. In my experience, this is one of the least well-known
aspects of C# 2, but it??™s useful enough to make it worth trying to enlighten your
coworkers rather than avoiding it.
There are two further aspects that increase the operator??™s usefulness, too.


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