"Unable to convert to IComparer"
I have the following IComparer defined for Blocked RegistryItem objects:
public class BoxedRegistryItemComparer : IComparer<object>
{
public int Compare(object left, object right)
{
RegistryItem leftReg = (RegistryItem)left;
RegistryItem rightReg = (RegistryItem)right;
return string.Compare(leftReg.Name, rightReg.Name);
}
}
I want to use this to sort the ArrayList from Boxed RegistryItems (it really should be List <RegistryItem
>, but that's out of my control).
ArrayList regItems = new ArrayList();
// fill up the list ...
BoxedRegistryItemComparer comparer = new BoxedRegistryItemComparer();
ArrayList.sort(comparer);
However, the last line gives a compiler error: "Unable to convert from BoxedRegistryItemComparer to System.Collections.IComparer". I would appreciate it if someone could point out my mistake.
source to share
You have defined Generic-Comparer ( IComparer<T>
) instead of Typeless Comparison ( IComparer
) . ArrayList.Sort()
expects not common IComparer
.
Generic types cannot be added to their non-equivalent equivalents.
source to share
If you have a situation where you have no control over Comparer or Sorter, here are two mini-classes that can convert between the two types (untested):
private class GenericComparer<T> : IComparer<T>
{
IComparer _Comparer;
public GenericComparer(IComparer comparer)
{
_Comparer = comparer;
}
public int Compare(T a, T b)
{
return _Comparer.Compare(a, b);
}
}
private class NonGenericComparer<T> : IComparer
{
IComparer<T> _Comparer;
public NonGenericComparer(IComparer<T> comparer)
{
_Comparer = comparer;
}
public int Compare(object a, object b)
{
return _Comparer.Compare((T)a, (T)b);
}
}
source to share