c-sharp
  1. c-sharp-shadowing-in-c

C# Shadowing in C#

In C#, shadowing is a mechanism where a subclass can define a member that has the same name and type as a member in the base class. Shadowing can be used to provide a new implementation of a base class member or to hide a base class member for a subclass. In this tutorial, we'll discuss how to use shadowing in C#.

Syntax

The syntax for shadowing a member in C# is as follows:

class BaseClass {
   public void Method1() {
      // code
   }
}
class SubClass : BaseClass {
   public new void Method1() {
      // code
   }
}

The new keyword is used to shadow the base class member.

Example

Let's say we have a base class called "Shape" that has a virtual method called "Draw". We can create a subclass called "Square" that shadows the "Draw" method by providing a new implementation:

class Shape {
   public virtual void Draw() {
      Console.WriteLine("Drawing a shape...");
   }
}
class Square : Shape {
   public new void Draw() {
      Console.WriteLine("Drawing a square...");
   }
}

Now, when we create an instance of the Square class and call the Draw method, the new implementation will be used:

Square square = new Square();
square.Draw(); // Output: "Drawing a square..."

Output

When we run the example code above, the output will be:

Drawing a square...

This is because we created an instance of the "Square" class and called the "Draw" method, which used the new implementation that shadows the base class method.

Explanation

In the example above, we created a base class called "Shape" that has a virtual method called "Draw". We then created a subclass called "Square" that shadows the "Draw" method by providing a new implementation.

When we create an instance of the Square class and call the Draw method, the new implementation will be used, which prints "Drawing a square..." to the console.

Use

Shadowing can be used to provide a new implementation of a base class member or to hide a base class member for a subclass. Shadowing can be useful when you need to customize the behavior of a class in a subclass.

Important Points

  • Shadowing can make code harder to read and maintain, so it should be used with caution.
  • When shadowing a method, use the new keyword to indicate that you're intentionally hiding the base class method.

Summary

In this tutorial, we discussed how to use shadowing in C# to provide a new implementation of a base class member or to hide a base class member for a subclass. We covered the syntax, example, output, explanation, use, and important points of shadowing in C#. With this knowledge, you can now use shadowing in your C# code to customize the behavior of a class in a subclass.

Published on: