DineshKumar
DineshKumar

Reputation: 487

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?

Upvotes: 14

Views: 2350

Answers (5)

Habib
Habib

Reputation: 223332

Your understanding that you are not inheriting from any class is not right.

See: Object.Equals Method (Object) - MSDN

Because the Object class is the base class for all types in the .NET Framework, the Object.Equals(Object) method provides the default equality comparison for all other types. However, types often override the Equals method to implement value equality.

But, remember to read: Not everything derives from object - Eric Lippert

Upvotes: 2

Rajat Srivastava
Rajat Srivastava

Reputation: 213

System.Object is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.

Thus all the class can override the method defined in this class. Methods defined in System.Object Class are Equals() ,Finalize() ,GetHashCode() and ToString().

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 157098

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 { }

Upvotes: 33

Rahul Tripathi
Rahul Tripathi

Reputation: 172578

Object class is the parent class for all the classes and all classes inherit from it. So your Default Class is also inheriting the Object class

This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.

You can understand this using a tree structure:

                     System.Object
                     /           \
                    /             \
                   /               \
SomeProject.DefaultClass        SomeProject.SomeOtherBaseClass
                                         /           \
                                        /             \
                                       /               \
                   SomeProject.ChildClass1       SomeProject.ChildClass2

On a side note also do check this very relevant article by Eric Lippert which may help you in understanding the Object class:- Not everything derives from object

Upvotes: 9

Mahesh Yallure
Mahesh Yallure

Reputation: 29

Object Class is the base class for all user defined classes , as you are created a class called DefaultClass , this will by sub class for Object class. So the Equals() method is already defined in the Object class hence you are going to overriding this method here.

Upvotes: 1

Related Questions