What is Shadowing

In one of my interview questions, I was asked what is shadowing? So, I thought, I should give it a try to answer it in my own way.

Shadowing we can say is the mechanism which allows us to change the type ( datatype to method) or method to datatype in inherited structure. Let us try it to understand with a very simple example.

  1. public class   Maths  
  2. {  
  3.    int  counter;  
  4.      
  5.    public Maths()  
  6.      {  
  7.         counter= 0;  
  8.      }   
  9.    
  10. }   
  11.    
  12. public class  Calculation : Maths  
  13. {  
  14.    public void  counter()  
  15.     {  
  16.         Console.WriteLine("This is  counter method");  
  17.     }   
  18. }  
  19.    
  20.  
  21. static void Main(string[] args)  
  22. {  
  23.   Maths objMaths = new Maths();  
  24.   objMaths.counter = 10;  
  25.   Console.WriteLine(objMaths.counter.ToString()); /// works as int datatype.  
  26.   Calculation docalculation = new Calculation();  
  27.   docalculation.counter(); /// counter works as the method.  
  28.   Console.ReadLine();  
  29. }  
As we can see from our code, when we create the instance of Maths class and use counter then it will be treated as the integer variable. And when we create the instance of Calculation and if we refer counter then it will work as method.

Conclusion : 

Shadowing is the mechanism in which the type ( variable.field.property, method) is the type which is defined at certain level of class in Inheritance hierarchy.

Please find source code to give it a try.