Export (0) Print
Expand All
3 out of 11 rated this helpful - Rate this topic

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
Not applicable.

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.

using System;

namespace Snippets {
    public class Temperature : IComparable {
        /// <summary>
        /// IComparable.CompareTo implementation.
        /// </summary>

        // The value holder
        protected double m_value;

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

        public double Value {
            get {
                return m_value;
            }
            set {
                m_value = value;
            }
        }

        public double Celsius {
            get {
                return (m_value - 32) / 1.8;
            }
            set {
                m_value = (value * 1.8) + 32;
            }
        }
    }
}

Windows 98, Windows Server 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 Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.