Skip to content

Instantly share code, notes, and snippets.

@AndrewBarfield
Created April 30, 2012 09:16
Show Gist options
  • Save AndrewBarfield/2556767 to your computer and use it in GitHub Desktop.
Save AndrewBarfield/2556767 to your computer and use it in GitHub Desktop.
C#: IComparable: Converting miles to kilometers
using System;
using System.Collections;
/*
* Sample Output
*
* 10 miles (16.09344 km)
* 86 miles (138.403584 km)
* 146 miles (234.964224 km)
* 214 miles (344.399616 km)
* 279 miles (449.006976 km)
* 326 miles (524.646144 km)
* 326 miles (524.646144 km)
* 355 miles (571.31712 km)
* 459 miles (738.688896 km)
* 482 miles (775.703808 km)
*/
namespace IComparableExample {
class Program {
static void Main(string[] args) {
ArrayList distances = new ArrayList();
Random rnd = new Random();
// Generate 10 random distances
for ( int ctr = 1 ; ctr <= 10 ; ctr++ ) {
int miles = rnd.Next( 1, 500 );
Distance dist = new Distance();
dist.Miles = miles;
distances.Add( dist );
}
// Sort the ArrayList (which calls on CompareTo)
distances.Sort();
// Displays the sorted distances
foreach ( Distance dist in distances )
Console.WriteLine( dist.Miles + " miles (" + dist.Kilometers + " km)" );
// Allow user to read output
Console.Read();
}
}
public class Distance : IComparable {
protected double distanceMiles;
// 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.
public int CompareTo(object obj) {
Distance otherDistance = obj as Distance;
if ( otherDistance != null )
return this.distanceMiles.CompareTo( otherDistance.distanceMiles );
else
throw new ArgumentException( "Object is not a Distance" );
}
public double Miles {
get {
return this.distanceMiles;
}
set {
this.distanceMiles = value;
}
}
public double Kilometers {
get {
return this.distanceMiles * 1.609344;
}
set {
this.distanceMiles = value / 1.609344;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment