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!
Comments
- Anonymous
April 26, 2006
Are you sure you didn't intend to say
IComparer _comparer;
public WeaklyTypedComparerWrapper(IComparer comparer)
{
_comparer = comparer;
} - Anonymous
April 26, 2006
The comment has been removed - Anonymous
April 26, 2006
The comment has been removed - Anonymous
May 05, 2006
The following links to .NET resources have been collated over time with the assistance of colleagues.&nbsp;...