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?
We can override the equals method in our class to check whether two objects have same data or not.
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.
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.
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.
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 { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With