Export (0) Print
Expand All

IComparable Interface

Defines a generalized comparison method that a value type or class implements to create a type-specific comparison method.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

[ComVisibleAttribute(true)] 
public interface IComparable
/** @attribute ComVisibleAttribute(true) */ 
public interface IComparable
ComVisibleAttribute(true) 
public interface IComparable

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.

The following code sample illustrates the implementation of IComparable and the requisite CompareTo method.

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;
        }
    }
}

public class Temperature implements IComparable
{
    /// <summary>
    /// IComparable.CompareTo implementation.
    /// </summary>
    public int CompareTo(Object obj)
    {
        if (obj instanceof Temperature) {
            Temperature temp = (Temperature)obj;
            return ((Int32)mValue).CompareTo(temp.mValue);
        }
        throw new ArgumentException("object is not a Temperature");
    } //CompareTo

    // The value holder
    protected int mValue;

    /** @property
     */
    public int get_Value()
    {
        return mValue;
    }//get_Value

    /** @property
     */
    public void set_Value(int value)
    {
        mValue = value;
    }//set_Value

    /** @property
     */
    public int get_Celsius()
    {
        return (mValue - 32) / 2;
    }//get_Celsius

    /** @property 
     */
    public void set_Celsius(int value)
    {
        mValue = value * 2 + 32;
    }//set_Celsius
} //Temperature

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft