6.
public static class PartialComparer
{
public static int? Compare
(T first, T second)
{
return Compare(Comparer.Default, first, second);
}
public static int? Compare(IComparer comparer,
T first,
T second)
{
int ret = comparer.Compare(first, second);
if (ret == 0)
{
return null;
}
return ret;
}
public static int? ReferenceCompare(T first, T second)
where T : class
Listing 4.6 Helper class for providing ???partial comparisons???
135 Novel uses of nullable types
{
if (first==second)
{
return 0;
}
if (first==null)
{
return -1;
}
if (second==null)
{
return 1;
}
return null;
}
}
The Compare methods in listing 4.6 are almost pathetically simple??”when a comparer
isn??™t specified, the default comparer for the type is used, and all that happens to the
comparison??™s return value is that zero is translated to null. The ReferenceCompare
method is longer but still very straightforward: it basically returns the correct comparison
result (??“1, 0, or 1) if it can tell the result just from the references, and null
otherwise. Even though this class is simple, it??™s remarkably useful. We can now
replace our previous product comparison with a neater implementation:
public int Compare(Product first, Product second)
{
return PC.ReferenceCompare (first, second) ??
// Reverse comparison of popularity to sort descending
PC.
Pages:
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282