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