What is Shadowing?

In C#, when a method in a base class is marked as sealed (also known as final in some languages), it means that the method cannot be overridden in derived classes. However, if you still need to provide a different implementation in a derived class, you can use method shadowing with the new keyword. Let’s explore this concept through an example:

using System;

// Base class with a sealed method
public class BaseClass
{
    public sealed void DisplayMessage()
    {
        Console.WriteLine("Message from BaseClass");
    }
}

// Derived class shadowing the sealed method
public class DerivedClass : BaseClass
{
    // Using the 'new' keyword to shadow the method
    public new void DisplayMessage()
    {
        Console.WriteLine("Message from DerivedClass");
    }
}

class Program
{
    static void Main()
    {
        // Creating instances of both base and derived classes
        BaseClass baseObj = new BaseClass();
        DerivedClass derivedObj = new DerivedClass();

        // Calling the sealed method on the base class instance
        baseObj.DisplayMessage(); // Output: Message from BaseClass

        // Calling the shadowed method on the derived class instance
        derivedObj.DisplayMessage(); // Output: Message from DerivedClass

        // Using polymorphism to call the method on the base class reference
        BaseClass polymorphicObj = new DerivedClass();
        polymorphicObj.DisplayMessage(); // Output: Message from BaseClass
    }
}

In this example, BaseClass has a sealed method DisplayMessage. The DerivedClass shadows this method using the new keyword, providing a different implementation. When calling the method on a DerivedClass instance, the shadowed method in the derived class is invoked. Note that when using polymorphism, i.e., assigning a DerivedClass instance to a BaseClass reference, the sealed method from the base class is still called.

Comments

Popular posts from this blog

How do I calculate a MD5 hash from a string?

What is WSDL?