locked
IComparer use RRS feed

  • Question

  • I'v created IComparer for SortedList collection but compiler do not like how I'm using it:

    class IntReverse : IComparer
    {   public int Compare(object x, object y)
        {  int xcopy = (int)x, ycopy = (int)y;
                if (xcopy > ycopy) return -1; else return 1;
          }
     }
      class Program
     {  static void Main()
         {  IComparer comp = new IntReverse();
             SortedList<int,string> a = new SortedList<int, string>(comp);
          }
     }

     Error message:
    Error    CS1503    Argument 1: cannot convert from 'System.Collections.IComparer' to 'int'   

    Friday, December 11, 2020 10:23 AM

All replies

  • Try another comparer:

    class IntReverse : IComparer<int>

    {

       public int Compare( int x, int y )

       {

          . . .

       }

    }
    . . .

    IComparer<int> comp = new IntReverse( );

    SortedList<int, string> a = new SortedList<int, string>( comp );


    Note that Compare must return 0 too. For example:

    class IntReverse : IComparer<int>

    {

       public int Compare( int x, int y )

       {

          return y - x;

       }

    }


    The documentation for IComparer<T> recommends deriving from the Comparer<T> abstract class instead of implementing the IComparer<T> interface.

    • Edited by Viorel_MVP Friday, December 11, 2020 5:17 PM
    Friday, December 11, 2020 5:15 PM
  • The error occurs because you are mixing up the non-Generic version of the comparer with the Generic version of the SortedList. You need to be consistent: Either both have to be Generic, or both non-Generic.

    For example, you can do

    ... new SortedList(comp)

    note that there is no <int, string>.

    Or you can create a class that is an IComparer<int> (instead of an IComparer) and then use this class to initialize a new SortedList<int, string>(comparer).

    But the way you have written it, the compiler thinks that you are calling this overload of the constructor for the Generic SortedList:

    SortedList<TKey,TValue>(Int32)

    and therefore it complains that it cannot convert from your IComparer to an int.

    Note that there is a different constructor like this:

    SortedList<TKey,TValue>(IComparer<TKey>)

    which presumably is the one that you were trying to invoke. But notice that this takes as an argument an IComparer<TKey>, which is not the same as an IComparer.


    Saturday, December 12, 2020 11:01 AM