user1804033
user1804033

Reputation: 51

Does not implement interface member 'System.Icomparable.CompareTo(object)'?

I got this message because I wrote a class implemented the Icomparable:

class Person: IComparable<Person>
    {
        public int age{get;set;}
        public String name { get; set; }

        int IComparable.CompareTo( Person p )
        {
            if (this.age > p.age)
                return 1;
            else if (this.age == p.age)
                return 0;
            else
                return -1;

        }

    }

Cannot figure out what was wrong in it, any one has any good ideas?

P.S., I changed the param into object but still not working

Upvotes: 0

Views: 5636

Answers (3)

Dan Hunex
Dan Hunex

Reputation: 5318

class Person : IComparable<Person>
{
    public int age { get; set; }
    public String name { get; set; }

    public int CompareTo(Person other)
    {
        if (age > other.age)

        { return 1; }
        if (age == other.age)
        { return 0; }
        return -1;
    }
}

Upvotes: 3

Brian Maupin
Brian Maupin

Reputation: 745

This is what your implementation should look like.

public int CompareTo(object obj)
    {
        Person p = obj as Person;
        if (this.age > p.age)
            return 1;
        else if (this.age == p.age)
            return 0;
        else
            return -1;
    }

Upvotes: 0

JaredPar
JaredPar

Reputation: 754525

The method declaration left off the generic argument. It needs to be

int IComparable<Person>.CompareTo(Person p)

Without the generic argument the compiler believes you are trying to implement the non-generic interface IComparable.

Upvotes: 4

Related Questions