IComparable interface

In this chapter you will learn:

  1. Use Array.Sort to sort object array

Sort IComparable

MyClass in the code below implements IComparable interface. Array.Sort method sorts array of MyClass by using CompareTo method.

using System;//from ja va2  s  .c o m
using System.Collections.Generic;
using System.Text;

class MyClass : IComparable
{
   public int TheValue;

   public int CompareTo(object obj)
   {
      MyClass mc = (MyClass)obj;

      if (this.TheValue < mc.TheValue)
         return -1;

      if (this.TheValue > mc.TheValue)
         return 1;

      return 0;
   }
}

class MainClass
{
   static void Main()
   {
      MyClass[] objectArray = new MyClass[5];
      for (int i = 0; i < 5; i++)
      {
         objectArray[i] = new MyClass();
         objectArray[i].TheValue = 100 - i;
      }

      foreach (MyClass i in objectArray)
         Console.Write("{0} ", i.TheValue);

      Array.Sort(objectArray);

      foreach (MyClass i in objectArray)
         Console.Write("{0} ", i.TheValue);
   }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Different IComparer for different ways to compare
Home » C# Tutorial » System Interface
ICloneable interface
IComparable interface
IComparer interface
IConvertible interface
IDisposable interface
IEnumerable interface
IEquatable interface
IFormatProvider interface
IFormattable interface