3/5/13

.NET interfaces - Part 1

I was re-reading some .net basics a couple of weeks ago just to refresh my memory and I came across some core interfaces that I had used in the past.

At that time i was not blogging and hadn't had a chance to write any posts about them. So I was thinking now is probably a good time to do it.

IComparable<T>


public interface IComparable<in T>
{       
  int CompareTo(T other);
}
When to use it:
Let us say you have a custom Type and you plan to use instances of that type in a collection. Whenever you are dealing with collections one of the obvious requirements is that the items in the collection be sortable.To facilitate this your custom Type needs to implement the CompareTo method of IComparable.

Code is as follows:

public class Texas : IComparable
{
        public string Name { get; set; }
        public int Population { get; set; }

/*
This method compares the population of the current instance with the input instance.
returns 0 if they are equal, 1 if this instance's population is greater than the input's population
and -1 if this instance's population is less than the input's population
*/
public int CompareTo(Texas input)
{
   if (this.Population < input.Population) return -1;
   if (this.Population == input.Population) return 0;
   return 1;
} 
}

//calling code

class Program
{

 static void Main(string[] args)
 {

  List lstTexas = new List();

  lstTexas.Add(new Texas() {Name = "Austin", Population = 500});
  lstTexas.Add(new Texas() {Name = "Houston", Population = 1500});
  lstTexas.Add(new Texas() {Name = "Dallas", Population = 900});
  lstTexas.Add(new Texas() {Name = "San Antonio", Population = 1200});
  lstTexas.Add(new Texas() {Name = "Waco", Population = 200});

  /*
     Sort internally calls the CompareTo method.The CompareTo method is 
     usually not called explicitly but is called from methods
     like the List<T>.Sort or Add(in a sorted list)
  */
   lstTexas.Sort();

  foreach (Texas city in lstTexas)
   Console.WriteLine(city.Name);

 }

}


//output - the cities are sorted in the ascending order of their populations
Waco
Austin
Dallas
San Antonio
Houston

NOTE: When you call Sort() with no arguments, you can only sort in ascending order OR descending order depending on your logic inside the CompareTo method. If you wish you can specify a sort order by using the overload of Sort that takes a Comparision delegate as an argument.

No comments: