Click here to Skip to main content
15,886,199 members
Articles / Programming Languages / C#

OOP Difference between Shadowing and Overriding

Rate me:
Please Sign up or sign in to vote.
3.69/5 (12 votes)
21 Dec 2016CPOL3 min read 31.2K   10   5
In this post, we will see the shadowing concept with respect to C# with a simple example.

Introduction

In this post, we will discuss the concept of Shadowing in OOP using C# and we will see how it works which will give you some idea about where we can use it and hopefully you will be able to decide when working practically in C# where it can be useful.

What is Shadowing

Shadowing is a concept of OOP (Object Oriented Programming) paradigm. Using Shadowing, we can provide a new implementation to base class member without overriding it, which means that the original implementation of base class member gets shadowed (hidden) with the new implementation of base class member provided in derived class.

Consider a scenario where you have an external assembly which you have added in your project. You have a class in that assembly and it has a method which is not defined as virtual and you want to override that method (define your own implementation for that method) in the derived class. What would you do?

This is the scenario where you can use shadowing concept to override the method in the derived class.

Definition

Following are few definitions of it.

According to MSDN

  • Shadowing is a concept of using Polymorphism in Object Oriented Programming. When two programming elements share the same name, one of them can hide, or shadow, the other one. In such a situation, the shadowed element is not available for reference; instead, when your code uses the element name, the compiler resolves it to the shadowing element.
  • Shadowing is actually hiding overridden method implementation in derived class and call the parent call implementation using derived class object

Difference Between Overriding and Shadowing

There is a major difference in shadowing and overriding which is normally when we override a virtual method in derived class and create instance of derived class and then if we hold reference to derived class object as base class object, and call that member, it always calls derived class implementation which is supposed to happen, but in shadowing the case is different, if for the same virtual member we shadow it in the derived class using new keyword and we call the implementation as above, it will call base class implementation when we have reference to object of type base class and if we have reference to same object of derived type, it will call derived type implementation so base class and derived class implementation are hidden from each other, method of which implementation to be called depends upon we are calling the member using reference of base type or derived type.

Example

Suppose I have a base class BaseLogger which has two virtual methods (means they can be overridden in subclass) defined:
C#
public abstract class BaseLogger
{
    public virtual void Log(string message)
    {
        Console.WriteLine("Base: " + message);
    }

    public virtual void LogCompleted()
    {
        Console.WriteLine("Completed");
    }
}

Now I create a class Logger that inherits from BaseLogger class. Logger class looks like this:

C#
public class Logger : BaseLogger
{
    public override void Log(string message)
    {
        Console.WriteLine(message);
    }

    public new void LogCompleted()
    {
        Console.WriteLine("Finished");
    }
}

Now I want my Console to print the following lines:

Log started!

Base: Log Continuing
 
Completed

What should I write in Main Program to get the above output? Here is the code we will need to write:

C#
public class Program
{
    public static void Main()
    {
        BaseLogger logger = new Logger();

        logger.Log("Log started!");
        logger.Log("Base: Log Continuing");
        logger.LogCompleted();
    }
}

The first call to Log method is OK, it has called Derived Logger class Log method and it should because we have overridden it in the Logger class.

The second call is also the same.

Now note the third call, it has called the base class LogCompleted() method not derived class, it is because we have defined derived class method with new keyword which is hiding the derived class method when we are calling it with object of type BaseLogger which is our base class, and if we hadn't put the new keyword, the compiler would think that the method hiding or shadowing to be done, and it would show a warning when you will compile it saying that:

Quote:

use the new keyword if hiding was intended

If we want to call the derived class LogCompleted() method, our object reference should be of type Logger not BaseLogger, while in method overriding, this is not the case.

In method overriding, if we cast object of derived class to base class and call method, it will call overridden implementation of derived class.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
Ehsan Sajjad is a Microsoft Certified Professional, Microsoft Certified C# Specialist and he is also among the top users on StackOverflow from Pakistan with 50k+ reputation at time of writing this and counting.

He is a passionate software developer with around 5 years of professional experience in Microsoft Technologies both web and desktop applications and always open to learn new things and platforms especially in mobile application development and game development.

Some Achievements :

  • 5th Top Contributor from Pakistan on Stackoverflow.com
  • Top User in ASP.NET MVC from Pakistan on Stackoverflow.com
  • 21st June 2017 - Article of the Day - ASP.NET Community (Beginners Guide on AJAX CRUD Operations in Grid using JQuery DataTables in ASP.NET MVC 5)
  • 19th April 2017 - Article of the Day - ASP.NET Community (ASP.NET MVC Async File Uploading using JQuery)
  • March 2017 - Visual C# Technical Guru Silver Medal on Microsoft Tech Net Wiki Article Competition
  • 20 January 2017 - Article of the Day - ASP.NET Community (Async File Uploading in ASP.NET MVC)
  • 22nd September 2016 - Article of the Day - ASP.NET Community (GridView with Server Side Filtering, Sorting and Paging in ASP.NET MVC 5)
  • 22nd August 2016 - Article of the Day - ASP.NET Community (Beginners Guide for Creating GridView in ASP.NET MVC 5)
  • December 2015 - C-SharpCorner Monthly Winner

Comments and Discussions

 
PraiseGood sharing ;) Pin
IBR_BAR24-Dec-16 20:47
IBR_BAR24-Dec-16 20:47 
QuestionIs shadowing really useful? Pin
Klaus Luedenscheidt22-Dec-16 19:33
Klaus Luedenscheidt22-Dec-16 19:33 
QuestionBugs! Pin
R.D.H.2-Mar-16 10:31
R.D.H.2-Mar-16 10:31 
GeneralMy vote of 5 Pin
Аslam Iqbal1-Mar-16 0:50
professionalАslam Iqbal1-Mar-16 0:50 
GeneralRe: My vote of 5 Pin
Ehsan Sajjad19-Apr-16 2:44
professionalEhsan Sajjad19-Apr-16 2:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.