First, it
doesn??™t just apply to nullable types??”reference types can also be used; you just can??™t
use a non-nullable value type for the first operand as that would be pointless. Also, it??™s
right associative, which means an expression of the form first ?? second ?? third is
evaluated as first ?? (second ?? third)??”and so it continues for more operands.
You can have any number of expressions, and they??™ll be evaluated in order, stopping
with the first non-null result. If all of the expressions evaluate to null, the result will be
null too.
As a concrete example of this, suppose you have an online ordering system (and
who doesn??™t these days?) with the concepts of a billing address, contact address, and
shipping address. The business rules declare that any user must have a billing address,
but the contact address is optional. The shipping address for a particular order is also
optional, defaulting to the billing address. These ???optional??? addresses are easily represented
as null references in the code. To work out who to contact in the case of a
problem with a shipment, the code in C# 1 might look something like this:
Address contact = user.ContactAddress;
if (contact==null)
{
contact = order.ShippingAddress;
if (contact==null)
{
contact = user.BillingAddress;
}
}
Using the conditional operator in this case is even more horrible.
Pages:
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274