Edit

Share via


IComparable.CompareTo(Object) Method

Definition

Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.

C#
public int CompareTo(object obj);
C#
public int CompareTo(object? obj);

Parameters

obj
Object

An object to compare with this instance.

Returns

A value that indicates the relative order of the objects being compared. The return value has these meanings:

Value Meaning
Less than zero This instance precedes obj in the sort order.
Zero This instance occurs in the same position in the sort order as obj.
Greater than zero This instance follows obj in the sort order.

Exceptions

obj is not the same type as this instance.

Examples

The following example illustrates the use of CompareTo to compare a Temperature object implementing IComparable with another object. The Temperature object implements CompareTo by simply wrapping a call to the Int32.CompareTo method.

C#
using System;
using System.Collections;

public class Temperature : IComparable
{
    // The temperature value
    protected double temperatureF;

    public int CompareTo(object obj) {
        if (obj == null) return 1;

        Temperature otherTemperature = obj as Temperature;
        if (otherTemperature != null)
            return this.temperatureF.CompareTo(otherTemperature.temperatureF);
        else
           throw new ArgumentException("Object is not a Temperature");
    }

    public double Fahrenheit
    {
        get
        {
            return this.temperatureF;
        }
        set 
        {
            this.temperatureF = value;
        }
    }

    public double Celsius
    {
        get
        {
            return (this.temperatureF - 32) * (5.0/9);
        }
        set
        {
            this.temperatureF = (value * 9.0/5) + 32;
        }
    }
}

public class CompareTemperatures
{
   public static void Main()
   {
      ArrayList temperatures = new ArrayList();
      // Initialize random number generator.
      Random rnd = new Random();

      // Generate 10 temperatures between 0 and 100 randomly.
      for (int ctr = 1; ctr <= 10; ctr++)
      {
         int degrees = rnd.Next(0, 100);
         Temperature temp = new Temperature();
         temp.Fahrenheit = degrees;
         temperatures.Add(temp);
      }

      // Sort ArrayList.
      temperatures.Sort();

      foreach (Temperature temp in temperatures)
         Console.WriteLine(temp.Fahrenheit);
   }
}
// The example displays the following output to the console (individual
// values may vary because they are randomly generated):
//       2
//       7
//       16
//       17
//       31
//       37
//       58
//       66
//       72
//       95

Remarks

The CompareTo method is implemented by types whose values can be ordered or sorted. It is called automatically by methods of non-generic collection objects, such as Array.Sort, to order each member of the array. If a custom class or structure does not implement IComparable, its members cannot be ordered and the sort operation can throw an InvalidOperationException.

This method is only a definition and must be implemented by a specific class or value type to have effect. The meaning of the comparisons specified in the Return Value section ("precedes", "occurs in the same position as", and "follows") depends on the particular implementation.

By definition, any object compares greater than (or follows) null, and two null references compare equal to each other.

The parameter, obj, must be the same type as the class or value type that implements this interface; otherwise, an ArgumentException is thrown.

Notes to Implementers

For objects A, B and C, the following must be true:

A.CompareTo(A) must return zero.

If A.CompareTo(B) returns zero, then B.CompareTo(A) must return zero.

If A.CompareTo(B) returns zero and B.CompareTo(C) returns zero, then A.CompareTo(C) must return zero.

If A.CompareTo(B) returns a value other than zero, then B.CompareTo(A) must return a value of the opposite sign.

If A.CompareTo(B) returns a value "x" not equal to zero, and B.CompareTo(C) returns a value "y" of the same sign as "x", then A.CompareTo(C) must return a value of the same sign as "x" and "y".

Notes to Callers

Use the CompareTo(Object) method to determine the ordering of instances of a class.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also