当前位置 > 首页 > Asp.net

Using IComparable<T> Interface

2010-4-12 8:08:00来源:Asp.net

Level : Beginner to Intermediate

C# language has constantly evolved over a constant period of time.Each new version introduced new features which changed the way we programmed and solved the problems. Whether it was introduction of generics in C# 2.0 , LINQ in C# 3.0 or concept of dynamic programming in C# 4.0 , each of them had or will have greater impact on our programming style.As a developer we don’t have much option but to evolve and redefine our self in this constantly changing environment. That said , I personally think that its even more important now to understand the fundamentals and central concept of C#. Its only through the proper understanding of these fundamental concepts , that we can get full grasp on advanced concepts like lambda expressions or LINQ. So with the overall intent being made clear , lets start with IComparable<T> interface.

IComparable<T>

Lets start with a very basic example wherein I will be creating a List of integer and then I will call the Sort() method on that list.

List<int> lstInt = new List<int>() { 23, 2, 1, 34, 12, 17 };
lstInt.Sort();
 
foreach (Int32 number in lstInt)
{
     Console.WriteLine(number.ToString());
}

OutPut :- 1,2,12,17,23,34

In here , Sort() method sort’s the list of integers. If we can recall from what we studied in data structures , sorting is implemented by algorithms like Bubble sort , merge sort etc.Internally .Net framework uses which sorting technique is not a matter of concern for us.All I know and care about is that , for sorting I should be able to compare two values. i.e. I should be able to compare 23 with 2. And in .Net framework types make themselves comparable by implementing IComparable<T> interface.So in the above case ,  integer type internally implements IComparable<T> interface.In short while we will see how Integer type implements IComparable<T> interface,but before that lets see the signature of IComparable<T> interface.

IComparable<T> Interface

   1:  public interface IComparable<T>
   2:  {
   3:      // Methods
   4:      int CompareTo(T other);
   5:  } 

Fairly simple , just one method which returns an integer.The possible values that CompareTo can return are –1 , 0 , 1. –1 is when initial value is less than the later one , 0 when both are equal and 1 when initial value is greater than later one.

   1:  if(a < b) 
   2:      return -1
   3:  else if(a > b)
   4:      return 1
   5:  else
   6:      return 0;

Next very quickly lets have a look at how System.Int32 type implements IComparable<T> interface.

   1:  public int CompareTo(int value)
   2:  {