Information Technology Reference
In-Depth Information
public
Customer(
string
name)
{
this
.name = name;
}
#region
IComparable<Customer> Members
public int
CompareTo(
Customer
other)
{
return
name.CompareTo(other.name);
}
#endregion
#region
IComparable Members
int
IComparable
.CompareTo(
object
obj)
{
if
(!(obj
is
Customer
))
throw new
ArgumentException
(
"Argument is not a Customer"
,
"obj"
);
Customer
otherCustomer = (
Customer
)obj;
return this
.CompareTo(otherCustomer);
}
#endregion
}
Notice that IComparable is explicitly implemented in this structure. That
ensures that the only code that will call the object-typed version of
CompareTo() is code that was written for the previous interface. There's
just too much to dislike about the classic version of IComparable. You've
got to check the runtime type of the argument. Incorrect code could legally
call this method with anything as the argument to the CompareTo method.
More so, proper arguments must be boxed and unboxed to provide the
actual comparison. That's an extra runtime expense for each compare.
Sorting a collection will make, on average n lg(n) comparisons of your object
using the IComparable.Compare method. Each of those will cause three
boxing and unboxing operations. For an array with 1,000 points, that will
be more than 20,000 boxing and unboxing operations, on average: n lg(n)
is almost 7,000, and there are 3 box and unbox operations per comparison.
Yo u m a y b e w o n d e r i n g w h y y o u s h o u l d i m p l e m e n t t h e n o n g e n e r i c
IComparable interface at all. There are two reasons. First, there's simple
backward compatibility. Your types will interact with code created before