Method Shadowing in C# (Method Hiding)

Method shadowing in C# is a technique where a derived class declares a method with the same name and signature as a method in the base class, effectively hiding the base class method.


Method Shadowing in C# or Method Hiding in C#:

Here is an example for method shadowing in c#

using System;

class BaseClass {
    public void Display() {
        Console.WriteLine("This is the base class.");
    }
}

class DerivedClass : BaseClass {
    public new void Display() {
        Console.WriteLine("This is the derived class.");
    }
}

class Program {
    static void Main(string[] args) {
        BaseClass baseObj = new BaseClass();
        DerivedClass derivedObj = new DerivedClass();

        baseObj.Display(); // Output: "This is the base class."
        derivedObj.Display(); // Output: "This is the derived class."

        BaseClass derivedAsBase = new DerivedClass();
        derivedAsBase.Display(); // Output: "This is the base class."
    }
}

In this example, we have a BaseClass with a Display method that prints a message to the console. We also have a DerivedClass that inherits from BaseClass and has its own Display method that prints a different message.

In the Main method, we create an instance of BaseClass and an instance of DerivedClass, and call their Display methods. As expected, the Display method of baseObj calls the method in BaseClass, while the Display method of derivedObj calls the method in DerivedClass.

However, when we create an instance of DerivedClass and assign it to a variable of type BaseClass, the Display method of derivedAsBase calls the method in BaseClass, not the one in DerivedClass. This is because the new keyword used in the Display method of DerivedClass shadows the method in BaseClass, and the shadowed method is not visible through a reference to the derived class.


– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Share this:
We will be happy to hear your thoughts

      Leave a reply

      www.troubleshootyourself.com
      Logo