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.
- public class Maths
- {
- int counter;
-
- public Maths()
- {
- counter= 0;
- }
-
- }
-
- public class Calculation : Maths
- {
- public void counter()
- {
- Console.WriteLine("This is counter method");
- }
- }
-
-
- static void Main(string[] args)
- {
- Maths objMaths = new Maths();
- objMaths.counter = 10;
- Console.WriteLine(objMaths.counter.ToString());
- Calculation docalculation = new Calculation();
- docalculation.counter();
- Console.ReadLine();
- }
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.