Shadowing in C# using new keyword

There are some situations where derived class needs to shadow the base class methods. C# provides a facility that is the logical opposite of method overriding termed shadowing. If the derived class defines a member that is same as member defined in a base class, then we call it as “the derived class has shadowed the base class.

 

Here I will explain with simple example. For example we have Base class which has display() method and Child class which also has method same name. Child class inherits Base class as shown below.

 

class Program
{
        static void Main(string[] args)
        {
            Child obj = new Child();
            obj.display();
            Console.ReadLine();
        }
    }
    class Base
    {
        public void display()
        {
            Console.WriteLine("This is from Base class");
        }
    }
    class Child :  Base
    {
        public void display()
        {
            Console.WriteLine("This is from Child class");
        }
    }

 

If you execute the above c ode you will get warning message as “’CSharpShadowing.Child.display()’ hides inherited member ‘CSharpShadowing.Base.display()’. Use the new Keyword if hiding was intended” as shown below.

 

 


To solve this issue, you have two options. You can use Override keyword for method in your child class and use virtual keyword for base class to extend the base class behavior. If you don’t have the permissions to access the base class code, you can use new keyword for your child class method to shadow the base class method as shown below.

 

class Program

{
        static void Main(string[] args)
        {
            Child obj = new Child();
            obj.display();
            Console.ReadLine();
        }
}

class Base
{
        public void display()
        {
            Console.WriteLine("This is from Base class");
        }
}
class Child :  Base
{
        public new void display()
        {
            Console.WriteLine("This is from Child class");
        }
}

 

In the above example, you are shadowing the Base class method display() in Child class by using new keyword. By using the new keyword you are able solve the warning message as we have before.

 

To discuss more about shadowing in C# or hiding in C# http://www.dotnetquestionanswers.com/index.php?topic=734.msg737#msg737

 

By using new keyword you can shadow base class variables, properties and methods. 

 

                                                                                                         CSharpShadowing.zip (20.98 kb)