IComparable and Sort in generic collection [KathyKam]

IComparable and Sort in generic collection [KathyKam]

  • Comments 4

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!

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

       public WeaklyTypedComparerWrapper(IComparer comparer)

       {

           _comparer = comparer;

       }
  • 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....


  • 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.
  • The following links to .NET resources have been collated over time with the assistance of colleagues.&amp;nbsp;...
Page 1 of 1 (4 items)