What is method overriding in C# inheritance? Explain with real time example

(Last Updated On: February 26, 2019)

Method overriding in c# with real time example – In c# interview, we need to explain overriding definition with program example and when to use method overriding in c# inheritance . We will explain method overriding with real time example for this interview question.

Answer: Method overriding is a feature that allows to invoke child class method having same name and signature as in base class method in inheritance hierarchy if we use base class reference.

In below c# inheritance source code , child class B overrides func() method of base class using override keyword and to allow override, we need to use virtual keyword before base class func() method.



Output: B : func()

When to Use method overriding in C# – Real time example

Let’s understand it with a real time example. We will take a scenario with program example where virtual and overriding not required. And later point of time we will tweak the same scenario and extend the same program example using virtual and overriding keywords.


Scenario: We have a DefaultSEO base class (SEO stands for Search Engine Optimization which is used for website optimization) having two operations AnalyseSEO() and LogReport(). A child class PageRankSEO will be derived from base class and will use base class methods to analyze SEO and log report using base class reference.

Note that in this scenario we don’t need to use virtual and override feature. C# program example given below



Output: Default : AnalyseSEO()

Lets tweak the scenario: Now  consider the advanced SEO i.e. PageRankSEO does not want to use base class AnalyseSEO() method for website optimization, but, want to use its own method. Secondly, we don’t have to change client source code that is code resides in main(). Then what is the solution?

Solution is to use C# virtual keyword with base class AnalyseSEIO() method i.e. public virtual void AnalyseSEO() and override it in child class using override keyword i.e.  public override void AnalyseSEO(). Now the program will call child class AnalyseSEO method without changing in main() source code.

Output: PageRankSEO : AnalyseSEO()