The IComparable and IComparableT Interfaces


The IComparable and IComparable<T> Interfaces

Many classes will need to implement either the IComparable or IComparable<T> interface because they enable one object to be compared to another by various methods defined by the C# library. Chapter 18 introduced the IComparable and IComparable<T> interfaces, where they were used to enable two objects of a generic type parameter to be compared. They were also mentioned in the discussion of Array, earlier in this chapter. However, because of their importance and applicability to many situations, they are formally examined here.

IComparable is especially easy to implement because it consists of just this one method:

 int CompareTo(object v)

This method compares the invoking object against the value in v. It returns greater than zero if the invoking object is greater than v, zero if the two objects are equal, and less than zero if the invoking object is less than v.

C# 2.0 added the generic version of IComparable, which is declared like this:

 public interface IComparable<T>

In this version, the type of data being compared is passed as a type argument to T. This causes the declaration of CompareTo( ) to be changed, as shown next:

 int CompareTo(T obj)

Here, the type of data upon which CompareTo( ) operates can be explicitly specified. This makes IComparable<T> type-safe. For this reason, IComparable<T> is now preferable to IComparable.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net