0

I have created a class Car that derives form the abstract class TransportMeans and implements an interface PrivateMeans which contains only one property:

interface PrivateMean 
{
int capacity { set; get; }
}

I want to implement a class thet sorts the objects of the class Car according to the property capacity. I want to do this by the use of the interface IComparer.

However, when I declare an additonal class CarComparer as follows:

public class CarComparer : IComparer<Car>
{

    int IComparer<Car>.Comparer(Car obj1, Car obj2)
    {
        PrivateMean t1 = (PrivateMean)obj1;
        PrivateMean t2 = (PrivateMean)obj2;


        if (t1 != null && t2 != null)
        {
            if (t1.capacity >= t2.capacity)
                return 1;
            else return -1;
        }
        else
            throw new ArgumentException("Some Parameter is not a Car!");
    }
}

I receive the error :

Error 1 'MeansOfTransport.CarComparer' does not implement interface member 'System.Collections.Generic.IComparer.Compare(MeansOfTransport.Car, MeansOfTransport.Car)'.

What is the problem?

Furthermore I am not allowed to use IComparer without a type definition (Car). Why?

NoWar
  • 36,338
  • 80
  • 323
  • 498
arjacsoh
  • 8,932
  • 28
  • 106
  • 166
  • `IComparer` and `IComparer` are different interfaces. The text of your question mentions one, while the code uses the other. If you want to use the non-templated version `IComparer`, you need to remove `` where you state the implemented interfaces, from where you implement the interface, and change the type parameters in the implementation to `object`. – Eric J. Feb 21 '12 at 17:31

2 Answers2

2

You have

int IComparer<Car>.Comparer(Car obj1, Car obj2)

You probably meant

int IComparer<Car>.Compare(Car obj1, Car obj2)
0

Possible problems:

  • You need to implement a Compare method, but yours is called Comparer
  • The method you are implementing is public, so yours should be too. Currently your method has no access modifier, so it will default to internal.
raveturned
  • 2,637
  • 24
  • 30