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?

Recommended Answers

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 …

Jump to Post

All 2 Replies

You have to cast a as an Employee

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.