Wednesday, January 1, 2014

Using IComparable in C#

In case you want to compare 2 objects for sorting purpose you can use this interface. IComparable defines a type specific comparison method. Value types and classes can implement this interface. 

Lets say you have a list of people and you want to sort it by age. You'll use Sort method comes with the list. Usually the Sort() method will use default comparer for the type specified by the generic argument, Here default comparer for Person. 


But it'll throw an error when trying to sort because Person does not have a comparer and it does not know how to sort them. Therefore you need to implement IComparable and its CompareTo method like below.


Now the sorting will happen successfully. Note that implementation of CompareTo(Object) must return a Int32. All numeric types such as Int32 and Double implements IComparable.


Resources

0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook