c# – Differences between method overriding and overriding

Question:

What is the difference between overriding and overriding a method?

Answer:

Overlapping (in your terms) means that a method in a derived class hides a method with the same signature in the base class.

Therefore, it is recommended in C# for derived class methods that override base class methods to use the new keyword. If you forget to do this, the compiler will warn you that you are hiding a function of the same name with the same signature in the base class.

For instance,

class Base
{
    public void Hello() { Console.WriteLine( "I'm the base class" ); }
}

class Derived : Base
{
    public new void Hello() { Console.WriteLine( "I'm the derived class" ); }
}

In this case, references to the Base class will always call the Hello method of the base class, and references to the derived class will always call the Hello method of the derived class.

For instance,

Base b = new Base();
b.Hello(); // I'm the base class

Derived d = new Derived();
d.Hello(); // I'm the derived class

b = d;
b.Hello(); // I'm the base class

The override applies to virtual functions. In a derived class, a virtual function is overridden. To do this, in the base class, the function must be defined with the keyword virtual (or abstract ), and in the derived class, to override it, you must specify another keyword override .

For instance,

class Base
{
    public virtual void Hello() { Console.WriteLine( "I'm the base class" ); }
}

class Derived : Base
{
    public override void Hello() { Console.WriteLine( "I'm the derived class" ); }
}

The difference with the previous example is that if the base class reference points to a derived class object, then the overridden function of the derived class will be called.

Base b = new Base();
b.Hello(); // I'm the base class

Derived d = new Derived();
d.Hello(); // I'm the derived class

b = d;
b.Hello(); `// I'm the derived class`

That is, the difference lies in these two sentences. In the first case, to cover

b = d;
b.Hello(); // I'm the base class
              ^^^^^^^^^^^^^^^^^^

and in the second case, under redefinition, we have

b = d;
b.Hello(); `// I'm the derived class`
            ^^^^^^^^^^^^^^^^^^^^^^^^

That is, in the first case, in each new derived class in the class hierarchy, we declare a new function that hides a function with the same signature in the base classes. And in the second case, the function with the same name is not re-declared, but the already declared function of the base class is redefined.

This allows you to dynamically call the correct definition of the same function, depending on the object with which the function is called.

Scroll to Top