"Cannot convert to IComparer"
Asked Answered
L

6

6

I have the following IComparer defined for boxed 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 an ArrayList of boxed RegistryItems (It really should be a 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 the compiler error: "Cannot convert from BoxedRegistryItemComparer to System.Collections.IComparer". I would appreciate it if someone could point out my mistake.

Lilly answered 28/9, 2009 at 13:58 Comment(0)
M
9

BoxedRegistryItemComparer should implement System.Collections.IComparer to be used with ArrayList.Sort. you implemented System.Collections.Generic.IComparer<T> which is not the same thing.

Moiety answered 28/9, 2009 at 14:4 Comment(0)
S
7

You've defined a Generic-Comparer (IComparer<T>) instead of a Comparer without a type (IComparer). ArrayList.Sort() expects a non-generic IComparer.

Generic-Types can not be casted into their non-generic equivalents.

Serviceberry answered 28/9, 2009 at 14:0 Comment(0)
G
4

In case you have a situation where you don't have any control over the Comparer or the Sorter, here are two mini-classes which 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);
    }
}
Grijalva answered 21/12, 2010 at 6:14 Comment(0)
J
1

Perhaps it is a crutch, but it works:

            arrayList.Sort(Comparer<object>.Create(
            (x, y) => ((RegistryItem)x).Name.CompareTo(((RegistryItem)y).Name)));
Jolty answered 18/11, 2017 at 8:39 Comment(0)
U
0
public class BoxedRegistryItemComparer : IComparer {
...
}
Unpleasantness answered 28/9, 2009 at 14:7 Comment(0)
T
0

An alternative to above post would be to have your comparer class implement both interfaces, then you can cast IComparer<T> to IComparer should you need both.

public class MyComparer<T> : IComparer<T>, IComparer
Tamqrah answered 4/5, 2011 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.