Price.CompareTo(second.Price);
if (ret != 0)
{
return ret;
}
return first.Name.CompareTo(second.Name);
}
This assumes that we won??™t be asked to compare null references, and that all of the
properties will return non-null references too. We could use some up-front null comparisons
and Comparer
.Default to handle those cases, but that would make the
code even longer and more involved. The code could be shorter (and avoid returning
from the middle of the method) by rearranging it slightly, but the fundamental ???compare,
check, compare, check??? pattern would still be present, and it wouldn??™t be as
obvious that once we??™ve got a nonzero answer, we??™re done.
Ah??¦ now, that last sentence is reminiscent of something else: the null coalescing
operator. As we saw in section 4.3, if we have a lot of expressions separated by ?? then
the operator will be repeatedly applied until it hits a non-null expression. Now all we??™ve
got to do is work out a way of returning null instead of zero from a comparison. This is
easy to do in a separate method, and that can also encapsulate the use of the default
comparer. We can even have an overload to use a specific comparer if we want. We??™ll
also deal with the case where either of the Product references we??™re passed is null. First,
let??™s look at the class implementing our helper methods, as shown in listing 4.
Pages:
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281