Information Technology Reference
In-Depth Information
public static bool operator
>=(
Customer
left,
Customer
right)
{
return
left.CompareTo(right) >=
0
;
}
}
That's all for the standard order of customers: by name. Later, you must
create a report sorting all customers by revenue. You still need the normal
comparison functionality defined by the Customer
struct
, sorting them
by name. Most APIs developed after generics became part of the .NET
Framework will ask for a Comparison<T> delegate to perform some other
sort. It's simple to create static properties in the Customer type that pro-
vide other comparison orders. For example, this delegate compares the
revenue generated by two customers:
public static
Comparison
<
Customer
> CompareByReview
{
get
{
return
(left,right) =>
left.revenue.CompareTo(right.revenue);
}
}
Older libraries will ask for this kind of functionality using the IComparer
interface. IComparer provides the standard way to provide alternative
orders for a type without using generics. Any of the methods delivered in
the 1.x .NET FCL that work on IComparable types provide overloads that
order objects through IComparer. Because you authored the Customer
struct
, you can create this new class (RevenueComparer) as a private
nested class inside the Customer
struct
. It gets exposed through a static
property in the Customer
struct
:
public struct
Customer
:
IComparable
<
Customer
>,
IComparable
{
private readonly string
name;
private double
revenue;
public
Customer(
string
name,
double
revenue)
{
this
.name = name;