IEquatable on Self Referential class

198 views Asked by At

Using a Form to grab input from a user to create it into an object (ToDo). The information is thrown into this self-referential class (ToDo) to create the object then is passed off to another class Queue.

The issue however is that I need to compare the following object that is passed, to other previous objects. If the object has the same name then don't throw the information to the Queue class.

But from my code the Equals method is not even executing. Just wondering what I am doing wrong here.

public class ToDo : IEquatable<ToDo>
{
    private string _name;
    private string _priority;

    private ToDo _next;
    private ToDo _previous;

    Queue queue = new Queue();


    public ToDo(string name, string priority)
    {

        _name = name;
        _priority = priority;

        _next = null;
        _previous = null;

        queue.Enqueue(this);

    }

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public string Priority
    {
        get { return _priority; }
        set { _priority = value; }
    }

    public ToDo Next
    {
        get { return _next; }
        set { _next = value; }
    }

    public ToDo Previous
    {
        get { return _previous; }
        set { _previous = value; }
    }



    public bool Equals(ToDo other)
    {
        if (ReferenceEquals(null, other)) 
            return false;
        if (ReferenceEquals(this, other)) 
            return true;

        return other.Name.Equals(Name);
    }

    public override bool Equals(object obj)
    {
        if (Object.ReferenceEquals(null, obj))

            return false;

        if (Object.ReferenceEquals(this, obj))

            return true;

        if (this.GetType() != obj.GetType())

            return false;

        return this.Equals(obj as ToDo);

    }

    public override int GetHashCode()
    {
        return this.Name.GetHashCode();
    }



}
1

There are 1 answers

0
reggaeguitar On

Here's an IEqualityComparer class you could use. The advantage of IEqualityComparer is that you can use this comparer in LINQ statements like

var todos1 = todos2.Except(todos3, new ToDoComparer());

public class ToDoComparer : IEqualityComparer<ToDo>
{
    public bool Equals(ToDo x, ToDo y)
    {
        //Check whether the compared objects reference the same data. 
        if (ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null. 
        if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
            return false;

        return x.Name.Equals(y.Name);
    }

    public int GetHashCode(ToDo todo)
    {            
        if (ReferenceEquals(todo, null) || todo.Name == null)
            return 0;
        return todo.Name.GetHashCode();
    }
}