C# Method Hiding/Shadowing
Syntax
class BaseClass
{
public virtual void Foo()
{
Console.WriteLine("BaseClass.Foo()");
}
}
class DerivedClass : BaseClass
{
public new void Foo()
{
Console.WriteLine("DerivedClass.Foo()");
}
}
Example
BaseClass obj1 = new BaseClass();
DerivedClass obj2 = new DerivedClass();
BaseClass obj3 = new DerivedClass();
obj1.Foo(); // Output: "BaseClass.Foo()"
obj2.Foo(); // Output: "DerivedClass.Foo()"
obj3.Foo(); // Output: "BaseClass.Foo()"
Output
The output of the program is:
BaseClass.Foo()
DerivedClass.Foo()
BaseClass.Foo()
Explanation
Method hiding or shadowing is a feature in C# that allows a derived class to provide a new implementation for a method that is already defined in a base class. The new implementation "hides" the original implementation from the derived class and any clients that use it, unless they specifically reference the base class.
In the example above, we have a base class BaseClass
with a virtual method Foo()
. The derived class DerivedClass
provides a new implementation of Foo()
using the new
modifier. When we create instances of BaseClass
, DerivedClass
, and assign an instance of DerivedClass
to a variable of type BaseClass
, and call the Foo()
method on each of them, we see that the output is different for the instance of DerivedClass
due to the method hiding.
Use
Method hiding or shadowing can be used to provide a specialized implementation of a method in a derived class that may not make sense in the base class. It can also be used to extend the behavior of a method in a base class without modifying the existing code.
Important Points
- Method hiding is used when a derived class wants to provide a new implementation of a method that is already defined in a base class.
- The
new
modifier can be used to indicate that a method is hiding a method in the base class. - The
virtual
modifier in the base class is required to enable the derived class to use thenew
modifier in the derived class to hide the method in the base class.
Summary
Method hiding or shadowing is a powerful feature in C# that lets a derived class provide a new implementation of a method defined in the base class. It can be used to provide specialized behavior in the derived class, or to extend the behavior of the method in the base class. The new
modifier is used to indicate that the method is hiding a method in the base class.