Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Posts Tagged ‘generic’

Reflection Comparer in C#

Posted by Jean Paul on December 30, 2010

I would like to share a piece of code that can save good amount of time.


You are having a Customer class with properties Ag, Dob, Name which are int, datetime and string respectively.

The Customer objects are stored in a list and for custom sorting them based on different properties, we need to write code by implementing IComparer.  This could be a tedious task if lots of UI screens are there and you need to write specific code for each screen.  The problem is worse if you wanted to sort ascending/descending and based on multiple properties.



You can accomplish the above by using the following class which implements IComparer interface.


The above class ‘ReflectionComparer’ has constructor which takes the property on which the object to be sorted.

The constructor takes multiple property names so that we can sort on multiple items.  There is one overloaded constructor too, which takes the SortOrder (Ascending/Descending).


You can just call the Sort method of the array/ArrayList and pass the instance of above class to it.

Eg: list.Sort(new ReflectionComparer("Age"));

ReflectionComparer Class Explained

It contains 2 constructors which are explained above.

There is one core method named Compare() which takes arguments x and y.

public int Compare(object x, object y)

For each objects passed – the corresponding CompareTo() method is called using Reflection.

The method GetMethodInfo() returns the “CompareTo” method info object.  Some optimizations were used there to reuse the same CompareTo() MethodInfo object to speed up the sorting process.

The method GetValue() returns the value of property to be compared.  Here also Reflection is the underlying mechanism.

Test Application

The attachment contains the test application which was created in Visual Studio 2008.  The test application provides us the UI to test various scenarios and their corresponding time taken for execution in seconds.



Eventhough Reflection comparison will be slower than normal comparisons, we can judiciously use the code above if the sorting speed is within our expectations.  The idea for the above comparer class is to minimize the coding effort on doing the comparison code infra.   In the above screen shot, 10 thousand records were sorted within 1 second in my computer having 3GHz speed.  Reflection is slower but your computer is many times faster than your requirement – then it is a right choice to use the code above.  Happy Coding.


You can download the source from: rocks!!

Posted in Reflection | Tagged: , , , | Leave a Comment »