What is Shadowing?

Shadowing makes the method of the parent class available to the child class without using the override keyword. It is also known as Method Hiding.

In the context of .NET, “shadowing” refers to the ability to define a member in a derived class with the same name as a member in the base class. This hides the base class member, effectively shadowing it, but does not override it.

Here’s a concise explanation:

  1. Shadowing: In this scenario, both the base class and the derived class have a member with the same name. However, the member in the derived class shadows the member in the base class. This means that when you refer to the member by name in the derived class, you’re referring to the one defined in the derived class, not the one in the base class.

Here’s a code example in C#:

csharp
using System;

class BaseClass
{
public void Print()
{
Console.WriteLine("BaseClass Print method");
}
}

class DerivedClass : BaseClass
{
public new void Print()
{
Console.WriteLine("DerivedClass Print method");
}
}

class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
obj.Print(); // This will call the Print method from DerivedClass
}
}

In this example, DerivedClass shadows the Print method from BaseClass using the new keyword. So, when you call Print on an instance of DerivedClass, it will call the Print method defined in DerivedClass, not the one defined in BaseClass.