Welcome to MSDN Blogs Sign in | Join | Help

IComparable and Sort in generic collection [KathyKam]

Someone asked me why you cannot pass in the non-generic IComparer to a generic collection (something like List<T>). Particularly, if a programmer using the .NET 2.0 framework and generic List (aka List<T>) is unable to pass custom legacy .NET Framework 1.1. IComparer implementation into the Sort() method.

 

In an effort to keep the design of generics really clean, we decided not to mix the generic and non generic model. To solve the above scenario, you can subclass IComparer<T>:IComparer. However, this would mean that all implementors of IComparer <T> would have to provide a non-generic implementation as well.

 

Ryan Byington gave me another great suggestion; create a thin wrapper for the IComparer implementation that implements IComparer<T>.

 

using System.Collections;

public class WeaklyTypedComparerWrapper<T> : IComparer<T>

{

    IComparer _comparer;

    public WeaklyTypedComparerWrapper(IComparer comparer)

    {

        _comparer = comparer;

    }

 

    public int Compare(T item1, T item2)

    {

        return _comparer.Compare(item1, item2);

    }

}

 

If you have a scenario where you *must* be able to pass in a non-generic version of IComparer to a generic collection, let us know!

Published Wednesday, April 26, 2006 11:51 AM by BCLTeam

Comments

Wednesday, April 26, 2006 3:58 PM by dimkaz

# re: IComparable and Sort in generic collection [KathyKam]

Are you sure you didn't intend to say
   IComparer _comparer;

   public WeaklyTypedComparerWrapper(IComparer comparer)

   {

       _comparer = comparer;

   }
Wednesday, April 26, 2006 4:06 PM by JamesCurran

# re: IComparable and Sort in generic collection [KathyKam]

If I followed this correctly, the line

IComparer<T> _comparer;

really wants to be:

IComparer _comparer;

Similarly, the next line wants to be:

public WeaklyTypedComparerWrapper(IComparer comparer)

As you have it, you are "converting" an IComparer<T> into an IComparer<T>, accompishing nothing....


Thursday, April 27, 2006 6:39 AM by Christoph Richter

# re: IComparable and Sort in generic collection [KathyKam]

the first thing, that comes in my mind is when you act with old ressources. and they need an IComparer and cant do anything with the new one.
Saturday, May 06, 2006 4:29 AM by mattonsoftware.com

# .NET Resources

The following links to .NET resources have been collated over time with the assistance of colleagues.&amp;nbsp;...
New Comments to this post are disabled
 
Page view tracker