Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I am able to override Equals method if my class doesn't inherit from anything?

I got bit confused how the following code works

public class DefaultClass
{
    public override bool Equals(object obj)
    {
        return base.Equals(obj);
    }
}

My question is: I am not inheriting any class but how am I still able to override Equals method. This code gets compiled perfectly in VS2010. Any idea how this works?

like image 982
DineshKumar Avatar asked Sep 11 '14 12:09

DineshKumar


People also ask

What is the reason for overriding equals () method?

We can override the equals method in our class to check whether two objects have same data or not.

Why are we not able to use the equals () method as is from the object class?

If we don't override equals() method, we won't be able to use those objects as a key in a hashtable. The equals() method in Object class uses only the == operator for comparisons, so unless we override equals(), two object are considered equal only if the two references refer to the same object.

What happens if you override equals but not hashCode?

If you only override the equals method, if a. equals(b) is true it means the hashCode of a and b must be the same but that does not happen since you did not override the hashCode method. Note : hashCode() method of Object class always returns a new hashCode for each object.

Can equals method be overridden?

You can override the equals method on a record, if you want a behavior other than the default. But if you do override equals , be sure to override hashCode for consistent logic, as you would for a conventional Java class.


1 Answers

Because your DefaultClass 'inherits' from object by default.

You are overriding object.Equals now.

I understand the confusion though. MSDN says that a class like that doesn't inherit any other class, but it does (object):

Inheritance: None. Example: class ClassA { }

like image 100
Patrick Hofman Avatar answered Sep 23 '22 04:09

Patrick Hofman