My previous two articles explained method hiding and method overriding.
In this article we will see the differences between the two with an example.
In my project, I created a ParentClass with a method named “ParentMethod”. I have also created a child class named “ChildClass” that is inheriting from the parent class.
- using System;
- namespace MethodOverridingMethodHiding {
- class ParentClass {
- public void ParentMethod() {
- Console.WriteLine("I am a parent method");
- }
- }
- class ChildClass : ParentClass {
- }
- }
To override a base class method, we need to make that method “virtual”.
- class ParentClass {
- public virtual void ParentMethod() {
- Console.WriteLine("I am a parent method");
- }
- }

It will generate the following code.
- class ChildClass : ParentClass {
- public override void ParentMethod() {
- base.ParentMethod();
- }
- }
- class ChildClass : ParentClass {
- public override void ParentMethod() {
- Console.WriteLine("I am overriding the parent class method");
- }
- }
- class Program {
- static void Main(string[] args) {
- ParentClass pc = new ChildClass();
- pc.ParentMethod();
- }
- }

Now let's look at an example where we will hide the base method rather than overriding it.
First, we need to remove the virtual keyword from the ParentMethod.
- class ParentClass {
- public void ParentMethod() {
- Console.WriteLine("I am a parent method");
- }
- }
- class ChildClass : ParentClass {
- public new void ParentMethod() {
- Console.WriteLine("I am overriding the parent class method");
- }
- }
- class Program {
- static void Main(string[] args) {
- ParentClass pc = new ChildClass();
- pc.ParentMethod();
- }
- }
The hidden parent class method will be invoked.

Note
But if you want to invoke the child class method, we can do the following in the main method:
- class Program {
- static void Main(string[] args) {
- ChildClass cc = new ChildClass();
- cc.ParentMethod();
- }
- }

From the preceding two examples it is very clear that in method overriding, a base class reference variable pointing to a child class object will invoke the overridden method in the child class and in method hiding, a base class reference variable pointing to a child class object will invoke the hidden method in the base class.


Pankajkumar PatelPosted Sep 4, 2019, 8:19 PM EDT
Nice article
Vijay SPosted Mar 18, 2015, 1:56 AM EDT
Informative
Gowtham RajamanickamTOP 100Posted Mar 17, 2015, 11:38 PM EDT
good show...
Harpreet SinghPosted Feb 4, 2015, 9:12 AM EST
Thank you :) Waltzy
WaltzyPosted Feb 4, 2015, 9:06 AM EST
Very clear explanation. Thanks!