Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Comparable Pairs


The solution rely on the generic class Pair<T,S> from an earlier exercise. To be as complete as possible, we first show Pair<T,S>:

using System;

public class Pair<S,T>{
  private S first;
  private T second;

  public Pair(S first, T second){
    this.first = first; this.second = second;
  }

  public S First{
     get {return first;}
  }

  public T Second{
     get {return second;}
  }
  
}

ComparablePair<T,U> is here:

using System;

public class ComparablePair<T,U>: Pair<T,U>, IComparable<ComparablePair<T,U>> 
  where T: IComparable<T>
  where U: IComparable<U> {

  public ComparablePair(T first, U second): base(first, second){
  }

  public int CompareTo(ComparablePair<T,U> other){
    int firstCompare = this.First.CompareTo(other.First);
    if (firstCompare != 0)
       return firstCompare;
    else 
       return this.Second.CompareTo(other.Second);
  }

}


Finally we show a client of ComparablePair<T,U>:

using System;

class App{

  public static void Main(){

    ComparablePair<int, bool> cp1 = new ComparablePair<int, bool>(4, false),
                              cp2 = new ComparablePair<int, bool>(4, true);

    int res = cp1.CompareTo(cp2);

    Console.WriteLine("Result of comparison: {0}", res);

  }

}

The program outputs:

Result of comparison: -1

The two First constituents are both 4, and thus equal to each other. The tow Second constituents are false and true, respectively. false is less than true (false.CompareTo(true) == -1), and therefore cp1.CompareTo(cp2) == -1.

This ends the solution to this exercise.