By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,724 Members | 863 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,724 IT Pros & Developers. It's quick & easy.

Generic Comparer Object

P: n/a
Hi All,

I have created my own generic comparer object which implements IComparer and
uses reflection. I have tested it and it seem to work fine but I am worried
about the way I did it. My goal was to not have to make a seperate Comparer
class for every field of my object that I wanted to sort like the
TimeTracker starter kit did. My Code is below. Basically to use it all I
have to do is to Create the GenericComparer object, set the CompareType and
CompareField properties, and pass it to the base.sort function of my custom
collection object. here is an example:

GenericComparer gcobj = new GenericComparer();
gcobj.CompareType = typeof(MyCustomObject);

I have tested speed on 1000 plus items in my collection
and it seem to be just as fast as making a separate Comparer Classes for
each field. I realize that the Framework will call my Compare method for
each object in the collection so should I be worried about using reflection
code in the method? Is calling reflection code processor intensive?
Please let me know if you have any opinions on the way I implemented this,
I want to learn the best way to do things.


Frank Wisniewski MCSE 4.0, MCP+I, A+
f p w 2 3 @ h o t m a i l . c o m

public class GenericComparer : IComparer
private Type _CompareType;
private string _CompareField;

public GenericComparer()

public Type CompareType
return _CompareType;
_CompareType = value;

public string CompareField
return _CompareField;
_CompareField = value;

public int Compare(object x, object y)
int ret;
object[] tempParams = new object[1];
tempParams[0] = y.GetType().GetProperty(_CompareField).GetValue(y,
object tempProp = x.GetType().GetProperty(_CompareField).GetValue(x,
ret = (int) tempProp.GetType().InvokeMember("CompareTo",
BindingFlags.InvokeMethod, null, tempProp, tempParams);
return ret;

Posted Via Premium Usenet Newsgroup Services
Nov 16 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.