Method Overriding In C#

We have seen how inheritance is implemented in C#. Let us now take a look into implementing method overriding, which provides you the flexibility of overriding methods of the base class.

To override an existing method of the base class, we declare a new method in the inherited class of the same name and prefix it with the new keyword.

Let us consider Example 10.

Example 10:

Method Overriding in C# Example 10

The output of the code in Example 10 will be

This is the Overridden Driver method of the class B

In Example 10 we have two methods with the name Driver, both in different classes. Note that class B overrides the Driver method of class A as it specifies the new keyword just before its definition of the Driver method.

Note, however, that even if you do not specify the new keyword before the second Driver() method the overriding would be performed and the output would be just the same. However, the compiler will throw a warning that the new keyword has not been specified. It is a good programming practice to use the new keyword.

Leave a comment