IComparable Interface defines a type-specific comparison : IComparable « Collections Data Structure « C# / C Sharp






IComparable Interface defines a type-specific comparison

 
using System;
using System.Collections;

public class Temperature : IComparable
{
    protected double temperatureF;

    public int CompareTo(object obj)
    {
        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();
        for (int i = 1; i <= 10; i++)
        {
            Temperature temp = new Temperature();
            temp.Fahrenheit = i;
            temperatures.Add(temp);
        }

        temperatures.Sort();

        foreach (Temperature temp in temperatures)
            Console.WriteLine(temp.Fahrenheit);

    }
}

   
  








Related examples in the same category

1.Creates and accesses an array of classes. Implements the IComparable interfaceCreates and accesses an array of classes. Implements the IComparable interface
2.Returns the index of the first occurrence in a sequence by using the default equality comparer.
3.Returns the index of the first occurrence in a sequence by using a specified IEqualityComparer.