Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling overriden virtual methods from the parent class

Say you were writing the original C# Object class and you wanted the following functionality:

  1. object1 == object2 will compare references unless this operator is overridden
  2. object1 != object2 will always return the inverse of the object's ACTUAL object1 == object2

So, for example, if I have a Bunny class (derived from Object) which uses ear lengths as its equals method, then the notequals method (inherited from Object) should return true if the bunnies have different ear lengths.

The problem that I see is that if I write my Object class something like:

public partial class Object {
    public virtual bool Equals(Object o2) {
       return (this === o2);
    }

    public bool NotEquals(Object o2) {
       return !this.Equals(o2);
    }
}

then it seems like that definition will bind NotEquals to Object's Equals, not the actual derived class's equals.

Is there some way that this can work without modifying C# itself in any way? I don't care so much that it's possible in C# but I care if there's some OOP principle which tells me that I shouldn't expect this sort of thing to work.

Also, I'm not sure whether or not this is fundamental to the question, but the idea is for NotEquals to be virtual as well so that it too can be overridden by derived classes which want their o1 != o2 to be different from !(o1 == o2). This question is inspired by this recent discussion.

like image 766
Rag Avatar asked Jan 26 '26 06:01

Rag


2 Answers

The code you've provided will call the derived Equals method. Equals is virtual, and that means that when it is called, the "most derived" implementation will be used.

like image 134
Paul Phillips Avatar answered Jan 27 '26 18:01

Paul Phillips


NotEquals will not bind to the Object class's equal method, it will use the most derived method. You could've easily tested this. And it's also easy to make notEquals virtual, so you could override that with custom logic as well.

Using these classes (ignore the horrible naming conventions):

class parent
{
    public virtual bool equals(parent p)
    {
        Console.WriteLine("parent equals");
        return false;
    }

    public virtual bool notEquals(parent p)
    {
        return !this.equals(p);
    }
}

class child : parent
{
    public override bool equals(parent p)
    {
        Console.WriteLine("child equals");
        return true;
    }
}

Then running this:

parent p = new parent();
p.notEquals(null);

child c = new child();
c.notEquals(null);

Results in this output:

parent equals
child equals
like image 37
Coeffect Avatar answered Jan 27 '26 18:01

Coeffect