Information Technology Reference
In-Depth Information
update the accessibility of different commands. Multiple actions can take
place in response to the same event.
When you have one function that handles one event in a derived class, the
override is the better approach. It is easier to maintain, more likely to be
correct over time, and more efficient. Reserve the event handlers for other
uses. Prefer overriding the base class implementation to attaching an event
handler.
Item 31: Implement Ordering Relations with IComparable<T>
and IComparer<T>
Yo u r t y p e s n e e d o r d e r i n g r e l a t i o n s h i p s t o d e s c r i b e h o w c o l l e c t i o n s s h o u l d
be sorted and searched. The .NET Framework defines two interfaces that
describe ordering relationships in your types: IComparable<T> and
IComparer<T>. IComparable defines the natural order for your types. A
type implements IComparer to describe alternative orderings. You can
define your own implementations of the relational operators (<, >, <=,
>=) to provide type-specific comparisons, to avoid some runtime ineffi-
ciencies in the interface implementations. This item discusses how to
implement ordering relations so that the core .NET Framework orders
your types through the defined interfaces and so that other users get the
best performance from these operations.
The IComparable interface contains one method: CompareTo(). This
method follows the long-standing tradition started with the C library
function strcmp: Its return value is less than 0 if the current object is less
than the comparison object, 0 if they are equal, and greater than 0 if the
current object is greater than the comparison object. IComparable<T>
will be used by most newer APIs in the .NET landscape. However, some
older APIs will use the classic IComparable interface. Therefore, when you
implement IComparable<T>, you should also implement IComparable.
IComparable takes parameters of type System.Object. You need to per-
form runtime type checking on the argument to this function. Every time
comparisons are performed, you must reinterpret the type of the argu-
ment:
public struct Customer : IComparable < Customer >, IComparable
{
private readonly string name;
 
 
Search WWH ::




Custom Search