Compare (second.Popularity, first.Popularity) ??
PC.Compare (first.Price, second.Price) ??
PC.Compare (first.Name, second.Name) ??
0;
}
As you may have noticed, I??™ve used PC rather than PartialComparer??”this is solely
for the sake of being able to fit the lines on the printed page. In real source I would
use the full type name and have one comparison per line. Of course, if you wanted
short lines for some reason, you could specify a using directive to make PC an alias
for PartialComparer??”I just wouldn??™t recommend it.
The final 0 is to indicate that if all of the earlier comparisons have passed, the two
Product instances are equal. We could have just used Comparer
.Default.
Compare(first.Name, second.Name) as the final comparison, but that would hurt the
symmetry of the method.
This comparison plays nicely with nulls, is easy to modify, forms an easy pattern to
use for other comparisons, and only compares as far as it needs to: if the prices are different,
the names won??™t be compared.
You may be wondering whether the same technique could be applied to equality
tests, which often have similar patterns. There??™s much less point in the case of equality,
because after the nullity and reference equality tests, you can just use && to provide the
136 CHAPTER 4 Saying nothing with nullable types
desired short-circuiting functionality for Booleans.
Pages:
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283