implements the IComparable interface : Compare « Collections Data Structure « C# / C Sharp

implements the IComparable interface

implements the IComparable interface

using System;

public class NewOrderedName : IComparable {
  private String firstName;
  private String lastName;
  public NewOrderedName(String f, String l) {
     firstName = f;
     lastName = l;

  public int CompareTo(Object o) {
    NewOrderedName name = (NewOrderedName)o;
    int lastResult = lastName.CompareTo(name.lastName);
    if (lastResult != 0)
      return lastResult;
    else {
      int firstResult = firstName.CompareTo(name.firstName);
      if (firstResult != 0)
         return firstResult;
         return 1;
  public static void Main() {
    NewOrderedName jAdams = new NewOrderedName("J", "A");
    NewOrderedName jqAdams = new NewOrderedName("A", "Q");
    NewOrderedName hAdams = new NewOrderedName("H", "S");
    Console.WriteLine ("jAdams vs. jqAdams {0}", jAdams.CompareTo(jqAdams)); 
    Console.WriteLine ("jAdams vs. hAdams {0}", jAdams.CompareTo(hAdams)); 
    Console.WriteLine ("hAdams vs. hAdams {0}", hAdams.CompareTo(hAdams)); 

Related examples in the same category

1.Use IComparerUse IComparer
2.Implement IComparableImplement IComparable
3.Sorting and Searching:Advanced Use of HashesSorting and Searching:Advanced Use of Hashes
4.Sorting and Searching:Using IComparerSorting and Searching:Using IComparer
5.Sorting and Searching:Implementing IComparableSorting and Searching:Implementing IComparable
6.Sorting and Searching:IComparer as a PropertySorting and Searching:IComparer as a Property