Information Technology Reference
In-Depth Information
The last version of the Customer struct , with the embedded Revenue-
Comparer, lets you order a collection of customers by name, the natural
order for customers, and provides an alternative order by exposing a class
that implements the IComparer interface to order customers by revenue.
If you don't have access to the source for the Customer class, you can still
provide an IComparer that orders customers using any of its public prop-
erties. You should use that idiom only when you do not have access to the
source for the class, as when you need a different ordering for one of the
classes in the .NET Framework.
Nowhere in this item did I mention Equals() or the == operator (see Item
6). Ordering relations and equality are distinct operations. You do not need
to implement an equality comparison to have an ordering relation. In fact,
reference types commonly implement ordering based on the object con-
tents, yet implement equality based on object identity. CompareTo()
returns 0, even though Equals() returns false. That's perfectly legal. Equal-
ity and ordering relations are not necessarily the same.
IComparable and IComparer are the standard mechanisms for providing
ordering relations for your types. IComparable should be used for the
most natural ordering. When you implement IComparable, you should
overload the comparison operators (<, >, <=, >=) consistently with our
IComparable ordering. IComparable.CompareTo() uses System.Object
parameters, so you should also provide a type-specific overload of the
CompareTo() method. IComparer can be used to provide alternative
orderings or can be used when you need to provide ordering for a type
that does not provide it for you.
Item 32: Avoid ICloneable
ICloneable sounds like a good idea: You implement the ICloneable inter-
face for types that support copies. If you don't want to support copies,
don't implement it. But your type does not live in a vacuum. Your decision
to support ICloneable affects derived types as well. Once a type supports
ICloneable, all its derived types must do the same. All its member types
must also support ICloneable or have some other mechanism to create a
copy. Finally, supporting deep copies is very problematic when you create
designs that contain webs of objects. ICloneable finesses this problem in
its official definition: It supports either a deep or a shallow copy. A shallow
copy creates a new object that contains copies of all member variables. If
those member variables are reference types, the new object refers to the
 
 
Search WWH ::




Custom Search