"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.

+2


source to share


6 answers


BoxedRegistryItemComparer

must implement System.Collections.IComparer

for use with ArrayList.Sort

. you have implemented System.Collections.Generic.IComparer<T>

which is not the same.



+6


source


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.

+7


source


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);
    }
}

      

+3


source


public class BoxedRegistryItemComparer : IComparer {
...
}

      

0


source


An alternative to the above post would be for your comparison class to implement both interfaces, then you can use IComparer <T> for IComparer if you need both.

public class MyComparer<T> : IComparer<T>, IComparer

      

0


source


It might be a crutch, but it works:

            arrayList.Sort(Comparer<object>.Create(
            (x, y) => ((RegistryItem)x).Name.CompareTo(((RegistryItem)y).Name)));

      

0


source







All Articles