Posts

Showing posts from January 11, 2009

How to use the IComparable and IComparer interfaces in Visual C#

How to use the IComparable and IComparer interfaces in Visual C# This step-by-step article describes the use of two interfaces: IComparer and IComparable. These interfaces are discussed in the same article for two reasons. These interfaces are frequently used together, and although the interfaces are similar (and have similar names), they serve different purposes. If you have an array of types (such as string or integer) that already support IComparer, you can sort that array without providing any explicit reference to IComparer. In that case, the elements of the array are cast to the default implementation of IComparer (Comparer.Default) for you. However, if you want to provide sorting or comparison capability for your custom objects, you must implement either or both of these interfaces. The following .NET Framework Class Library namespace is referenced in this article: System.Collections IComparable: The role of IComparable is to provide a method of comparing two objects of a partic