C# Shadowing using new Keyword

 

Whenever we want to override the Base class methods in Child class, generally we declare the Base class methods with virtual keyword and in Child class we will use override keyword to override the Base class method, this is called Overriding.

But in some situations where our Base class methods does not declare with the virtual keyword, still we can override the Base class method in the Child class but we cannot use override keyword as shown below. 

class Base 

{ 

        public string GetData() 

        { 

            return "This is from Main class"; 

        } 

} 

 

class Child : Base 

{ 

        public string GetData() 

        { 

            return "This is from Child class"; 

        } 

}

 

But we will get the warning message like “'CSharpShadowing.Child.GetData()' hides inherited member 'CSharpShadowing.Main.GetData()'. Use the new keyword if hiding was intended” as shown below.

 

To avoid this type of warning message we have to use “new” keyword in Child class to hide the Base class method and this is called Shadowing the Base class method. As shown below use the “new” keyword in Child class method to hide the Base class method. 

using System;

 

namespace CSharpShadowing 

{ 

    class Program 

    { 

        static void Main(string[] args) 

        { 

            Child obj = new Child(); 

            Console.WriteLine(obj.GetData()); 

            Console.ReadLine(); 

        } 

    }

 

    class Base 

    { 

        public string GetData() 

        { 

            return "This is from Main class"; 

        } 

    }

 

    class Child : Base 

    { 

        public new string GetData() 

        { 

            return "This is from Child class"; 

        } 

    } 

}

 

We have to use Shadowing whenever we want to override the Base class method but Base class method is not declared with the virtual keyword and we don’t have permissions to access the Base class method.

                                                                                                                         CSharpShadowing.zip (21.95 kb)