C# - Advantages/Disadvantages of different implementations for Comparing Objects

Posted by Kevin Crowell on Stack Overflow See other posts from Stack Overflow or by Kevin Crowell
Published on 2010-03-21T18:56:59Z Indexed on 2010/03/21 19:01 UTC
Read the original article Hit count: 266

Filed under:
|
|

This questions involves 2 different implementations of essentially the same code.

First, using delegate to create a Comparison method that can be used as a parameter when sorting a collection of objects:

class Foo
{
    public static Comparison<Foo> BarComparison = delegate(Foo foo1, Foo foo2)
    {
        return foo1.Bar.CompareTo(foo2.Bar);
    };
}

I use the above when I want to have a way of sorting a collection of Foo objects in a different way than my CompareTo function offers. For example:

List<Foo> fooList = new List<Foo>();
fooList.Sort(BarComparison);

Second, using IComparer:

public class BarComparer : IComparer<Foo>
{
    public int Compare(Foo foo1, Foo foo2)
    {
        return foo1.Bar.CompareTo(foo2.Bar);
    }
}

I use the above when I want to do a binary search for a Foo object in a collection of Foo objects. For example:

BarComparer comparer = new BarComparer();
List<Foo> fooList = new List<Foo>();
Foo foo = new Foo();
int index = fooList.BinarySearch(foo, comparer);

My questions are:

  • What are the advantages and disadvantages of each of these implementations?
  • What are some more ways to take advantage of each of these implementations?
  • Is there a way to combine these implementations in such a way that I do not need to duplicate the code?
  • Can I achieve both a binary search and an alternative collection sort using only 1 of these methods?

© Stack Overflow or respective owner

Related posts about c#

Related posts about icomparer