13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Novel uses of nullable types135}{}if (first==second){return 0;}if (first==null){return -1;}if (second==null){return 1;}return null;The Compare methods <strong>in</strong> list<strong>in</strong>g 4.6 are almost pathetically simple—when a comparerisn’t specified, the default comparer for the type is used, and all that happens to thecomparison’s return value is that zero is translated to null. The ReferenceComparemethod is longer but still very straightforward: it basically returns the correct comparisonresult (–1, 0, or 1) if it can tell the result just from the references, and nullotherwise. Even though this class is simple, it’s remarkably useful. We can nowreplace our previous product comparison with a neater implementation:public <strong>in</strong>t Compare(Product first, Product second){return PC.ReferenceCompare (first, second) ??// Reverse comparison of popularity to sort descend<strong>in</strong>gPC.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 solelyfor the sake of be<strong>in</strong>g able to fit the l<strong>in</strong>es on the pr<strong>in</strong>ted page. In real source I woulduse the full type name and have one comparison per l<strong>in</strong>e. Of course, if you wantedshort l<strong>in</strong>es for some reason, you could specify a us<strong>in</strong>g directive to make PC an aliasfor PartialComparer—I just wouldn’t recommend it.The f<strong>in</strong>al 0 is to <strong>in</strong>dicate that if all of the earlier comparisons have passed, the twoProduct <strong>in</strong>stances are equal. We could have just used Comparer.Default.Compare(first.Name, second.Name) as the f<strong>in</strong>al comparison, but that would hurt thesymmetry of the method.This comparison plays nicely with nulls, is easy to modify, forms an easy pattern touse 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 wonder<strong>in</strong>g whether the same technique could be applied to equalitytests, which often have similar patterns. There’s much less po<strong>in</strong>t <strong>in</strong> the case of equality,because after the nullity and reference equality tests, you can just use && to provide theLicensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!