Reputation: 21
I was wondering why is Object.Equals(Object obj)
virtual. I understand that we can override that method and write our own code for checking equality instead of the base Object.Equals(Object obj)
method that checks only reference equality.
What I say is why override it when i can implement my own new method in my defined type? Is there any specific reason?
Upvotes: 2
Views: 641
Reputation: 62498
What I say is why override it when i can implement my own new method in my defined type?
Because that is how the language feature has been designed, as you know every type in C# is inheriting from Object
and Object
defines the methods with default implementation to check equality of two objects, and we as developers creating new types might want to modify the behavior how equals method compare two objects of specific type.
Here is an example to understand why it is virtual:
int i = 1;
int j = 1;
Object o = i;
o.Equals(j); // now what will happen here if you have'nt overriden it
the int
type contains the overriden implementation of Equals
method which checks the two integers for equality, so when we will call Equals
method using reference of type Object
it will call the implementation defined in the type System.Int32
,and we had a new method defined in the System.Int32
and not override the Equals
method of Object
, then we would see unexpected behavior as Object
type implementation would have checked the memory addresses i.e reference equality.
Consider this example as well:
public class Person
{
private string _name;
public string Name
{
get
{
return _name;
}
}
public Person(string name)
{
_name = name;
}
public override string ToString()
{
return _name;
}
}
What if i want Equals
method to not compare them by reference but instead we want to compare them on basis of name
, in that case we would need to override
the Equals
method so that calling it either with Object
type reference or Person
type reference it would return the same result i.e not checking reference equality but checking the Name
of two Person
class objects.
Upvotes: 1
Reputation: 35318
You would override it for the same reason you would want to override any method rather than hiding it with a new method in a derived class: because of polymorphism. You don't know how your derived class is going to be used by other code which only might know about the base class.
Clients may not even know that you've overridden the class at all, but they do know that they can call Equals
on your instances because everything derives from Object
. If you have some other, new method, the code using your instances will not know to call that method instead. It's the Liskov Substitution Principle at work.
Upvotes: 1