tags:

views:

55

answers:

2

Let's have this code :

class student :IComparable , IComparable<student> 
{
    public string name = "";

    public override string ToString()
    {
        return name; 
    }

    #region IComparable Members

    public int CompareTo(object obj)
    {
        if (this.name.Equals(((student)obj).name ) )
            return 0 ; 
        else
            return -1 ; 
    }

    #endregion

    #region IComparable<student> Members

    public int CompareTo(student other)
    {
        if (this.name.Equals (other.name )) 
            return 0 ; 
        else
            return -1 ; 
    }

    #endregion
}

I am create LinkedList from this class in Main Like :

LinkedList<student> list = new LinkedList<student>(); 
list.AddLast(new student { name="Farah"}); 
list.AddLast(new student { name="Noor"}); 
list.AddLast(new student { name="Reem"});

foreach (student s in list)
{
    Console.WriteLine(s);
}

it's print : Farah Noor REEM

but when I am try to search about any element it doesn't find it , Like :

Console.WriteLine(list.Contains(new student{ name="Noor"})); 

This Print false although "student" class implements "IComparable , IComparable" !!

What should I do to work ??

+2  A: 

The problem, that Contains doesn't works with IComparable interface. It uses Equals method. SO override it:

    public override bool Equals(object obj)
    {
        return this.CompareTo(((IComparable)obj)) == 0;
    }
Dewfy
Why the cast to `IComparable`?
dalle
@dalle - just to make dramatic accent :)
Dewfy
Casting to `Student` would be more appropriate, and saves a minuscule of instructions.
dalle
@dalle - because Dewfy used CompareTo method :)
Farah_online
@Farah_online: The parameter to `IComparable.CompareTo` is of type `object`. The parameter to `IComparable<T>.CompareTo` is of type `T`. Casting to `IComparable` makes no sense, but of course `IComparable` is convertible to `object`. Casting to `Student` would result in the `IComparable<Student>.CompareTo` method being called, which then "saves" one cast, alas the saving of a minuscule of instructions.
dalle
+1  A: 

Implement Equals and GetHashCode for your student class.

Mark Byers