Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not entering Equals() method in a class derived from Object

In the exact setup:

namespace NS
{
    class Program
    {
        static void Main(string[] args)
        {
            Object obj1 = new A();
            Object obj2 = new A();
            Console.WriteLine(obj1.GetType());
            Console.WriteLine(obj2.GetType());

            Console.WriteLine(obj1.Equals(obj2)); // why not entering A::Equals(A a)
            Console.ReadLine();
        }
    }
    class A
    {
        int x;
        public bool Equals(A a)
        {
            Console.WriteLine("enters Equals");
            return this.x == a.x;
        }
    }
}

I have the output from console app in C#:

NS.A
NS.A
False

Question: If ojb1 and obj1 are of type NS.A why public bool Equals(A a) is not entered?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is Console.WriteLine(obj1.GetType()); "lies" about a real object type. I am confused?

I wanted to call A.Equals(A) method from code even though Object obj1 = new A();

I know I can fix the problem with A obj1 = new A(); but I am stuck with understanding why GetType() returns the A and I cannot call the A.Equals(A).

>Solution :

You need to let it know it is overriding and not creating a new function.

    public override bool Equals(object a)
    {
        Console.WriteLine("enters Equals");
        return ((A)this).x == ((A)a).x;
    } 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading