13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

134 CHAPTER 4 Say<strong>in</strong>g noth<strong>in</strong>g with nullable types}if (ret != 0){return ret;}ret = first.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 theproperties will return non-null references too. We could use some up-front null comparisonsand Comparer.Default to handle those cases, but that would make thecode even longer and more <strong>in</strong>volved. The code could be shorter (and avoid return<strong>in</strong>gfrom the middle of the method) by rearrang<strong>in</strong>g it slightly, but the fundamental “compare,check, compare, check” pattern would still be present, and it wouldn’t be asobvious that once we’ve got a nonzero answer, we’re done.Ah… now, that last sentence is rem<strong>in</strong>iscent of someth<strong>in</strong>g else: the null coalesc<strong>in</strong>goperator. As we saw <strong>in</strong> section 4.3, if we have a lot of expressions separated by ?? thenthe operator will be repeatedly applied until it hits a non-null expression. Now all we’vegot to do is work out a way of return<strong>in</strong>g null <strong>in</strong>stead of zero from a comparison. This iseasy to do <strong>in</strong> a separate method, and that can also encapsulate the use of the defaultcomparer. We can even have an overload to use a specific comparer if we want. We’llalso deal with the case where either of the Product references we’re passed is null. First,let’s look at the class implement<strong>in</strong>g our helper methods, as shown <strong>in</strong> list<strong>in</strong>g 4.6.List<strong>in</strong>g 4.6Helper class for provid<strong>in</strong>g “partial comparisons”public static class PartialComparer{public static <strong>in</strong>t? Compare(T first, T second){return Compare(Comparer.Default, first, second);}public static <strong>in</strong>t? Compare(IComparer comparer,T first,T second){<strong>in</strong>t ret = comparer.Compare(first, second);if (ret == 0){return null;}return ret;}public static <strong>in</strong>t? ReferenceCompare(T first, T second)where T : classLicensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!