Prev | Current Page 263 | Next

Jon Skeet

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

Using the null coalescing
operator, however, makes the code very straightforward:
Address contact = user.ContactAddress ??
order.ShippingAddress ??
user.BillingAddress;
If the business rules changed to use the shipping address by default instead of the
user??™s contact address, the change here would be extremely obvious. It wouldn??™t be
131 Novel uses of nullable types
particularly taxing with the if/else version, but I know I??™d have to stop and think
twice, and verify the code mentally. I??™d also be relying on unit tests, so there??™d be relatively
little chance of me actually getting it wrong, but I??™d prefer not to think about
things like this unless I absolutely have to.
NOTE Everything in moderation??”Just in case you may be thinking that my code is
littered with uses of the null coalescing operator, it??™s really not. I tend to
consider it when I see defaulting mechanisms involving nulls and possibly
the conditional operator, but it doesn??™t come up very often. When its use
is natural, however, it can be a powerful tool in the battle for readability.
We??™ve seen how nullable types can be used for ???ordinary??? properties of objects??”cases
where we just naturally might not have a value for some particular aspect that is still
best expressed with a value type. Those are the more obvious uses for nullable types
and indeed the most common ones.


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