arjacsoh
arjacsoh

Reputation: 9242

IComparer based on property of an interface

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?

Upvotes: 0

Views: 1213

Answers (2)

raveturned
raveturned

Reputation: 2677

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.

Upvotes: 0

You have

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

You probably meant

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

Upvotes: 2

Related Questions