Defines a generalized comparison method that a value type or class implements to create a type-specific comparison method.
For a list of all members of this type, see IComparable Members.
[Visual Basic] Public Interface IComparable [C#] public interface IComparable [C++] public __gc __interface IComparable [JScript] public interface IComparable
| Class | Description |
|---|---|
| Enum | Provides the base class for enumerations. |
| String | Represents text; that is, a series of Unicode characters. |
| Version | Represents the version number for a common language runtime assembly. This class cannot be inherited. |
This interface is implemented by types whose values can be ordered; for example, the numeric and string classes.
A value type or class implements the CompareTo method to create a type-specific comparison method suitable for purposes such as sorting.
[Visual Basic, C#, C++] The following code sample illustrates the implementation of IComparable and the requisite CompareTo method.
[Visual Basic] Public Class Temperature Implements IComparable Public Overloads Function CompareTo(ByVal obj As Object) As Integer _ Implements IComparable.CompareTo If TypeOf obj Is Temperature Then Dim temp As Temperature = CType(obj, Temperature) Return m_value.CompareTo(temp.m_value) End If Throw New ArgumentException("object is not a Temperature") End Function ' The value holder Protected m_value As Integer Public Property Value() As Integer Get Return m_value End Get Set(ByVal Value As Integer) m_value = Value End Set End Property Public Property Celsius() As Integer Get Return (m_value - 32) / 2 End Get Set(ByVal Value As Integer) m_value = Value * 2 + 32 End Set End Property End Class [C#] public class Temperature : IComparable { /// <summary> /// IComparable.CompareTo implementation. /// </summary> public int CompareTo(object obj) { if(obj is Temperature) { Temperature temp = (Temperature) obj; return m_value.CompareTo(temp.m_value); } throw new ArgumentException("object is not a Temperature"); } // The value holder protected int m_value; public int Value { get { return m_value; } set { m_value = value; } } public int Celsius { get { return (m_value-32)/2; } set { m_value = value*2+32; } } } [C++]
[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button
in the upper-left corner of the page.
Namespace: System
Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework - Windows CE .NET
Assembly: Mscorlib (in Mscorlib.dll)