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.