0

Give then following Class declaration:

   class Employee {
        public string Name { get; set; }
        public int Age { get; set; }

        public override bool Equals(object obj)
        {
            Console.WriteLine("In Equals(Object)");

            if (obj is Employee)
                if (this.Name == (obj as Employee).Name && this.Age == (obj as Employee).Age)
                    return true;
                else
                    return false;
            else
                return false;
        }

        public bool Equals(Employee obj)
        {
            Console.WriteLine("In Equals(Employee)");

            return this.Equals(obj as Object);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }

I'm trying to use Employee.Equals(Employee) but for some reason it doesn't work:

    private static void CompareObjects(Object a, Object b)
    {        
        if (a.Equals(b as Employee)) Console.WriteLine("a.Equals(b) returns true");
        else Console.WriteLine("a.Equals(b) returns false");
    }

As I'm casting b as Employee, I was expecting that Employee.Equals(Employee) would be called, since it matches the signature better then Employee.Equals(Object), but the latter is being called instead. What am I doing wrong?

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by Momerath
1

To expand further on this, what is happening is that a is being treated as type Object, which only has one form of the Equals method. So even though you cast b into type Employee, it gets recast into type Object (as that is what matches the Object.Equals method). The system then checks if there is an overload of the Equals method and finds your Equals(object) method and uses that.

Edited by Momerath

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.