Understanding Shadowing in C#: A Comprehensive Guide

├Źndice
  1. What is Shadowing in C#?
  2. Why is Shadowing Necessary?
  3. How Does Shadowing Work?
  4. Examples of Shadowing in C#
  5. Conclusion

What is Shadowing in C#?

Shadowing is a term used in C# to refer to the process of hiding a variable, method or property of a base class by defining a variable, method or property with the same name in a derived class. Shadowing is also known as name hiding or variable hiding.

Why is Shadowing Necessary?

Shadowing is necessary when a derived class needs to have its own definition of a variable, method or property with the same name as that of the base class. This allows the derived class to have its own implementation of the variable, method or property, without affecting the base class definition.

How Does Shadowing Work?

When a derived class defines a variable, method or property with the same name as that of the base class, the derived class is said to have shadowed the base class variable, method or property. The shadowed variable, method or property can still be accessed by using the base keyword.

Examples of Shadowing in C#

Here is an example of shadowing a variable in C#:


class Base
{
    public int x = 10;
}

class Derived : Base
{
    public int x = 20;
    
    public void Show()
    {
        Console.WriteLine("Base x = {0}", base.x); // Accessing the base class variable
        Console.WriteLine("Derived x = {0}", x); // Accessing the derived class variable
    }
}

In this example, the derived class has defined a variable with the same name as that of the base class. The Show method in the derived class accesses both the base class variable and the derived class variable using the base keyword and the variable name respectively.

Here is an example of shadowing a method in C#:


class Base
{
    public void Show()
    {
        Console.WriteLine("Base Show");
    }
}

class Derived : Base
{
    public new void Show()
    {
        Console.WriteLine("Derived Show");
    }
}

In this example, the derived class has defined a method with the same name as that of the base class. The new keyword is used to indicate that the method in the derived class is intended to shadow the method in the base class.

Conclusion

Shadowing is a powerful feature in C# that allows a derived class to define its own implementation of a variable, method or property with the same name as that of the base class. While shadowing can be useful in certain situations, it should be used with caution to avoid confusion and maintain code readability.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information