25 Feb 2024
In C#, method hiding refers to the ability to define a new method in a derived class with the same name as a method in the base class. This new method "hides" the method in the base class, and the behavior that gets executed depends on the type of the object that calls the method.
Method hiding is achieved by using the new keyword in the derived class. When a method in a derived class is declared with the new modifier, it indicates that the method is intentionally hiding a member in the base class, and it is not an override of the base class method.
Example to illustrate method hiding in C#:
class BaseClass
{
public void Display()
{
Console.WriteLine("BaseClass Display");
}
}
class DerivedClass : BaseClass
{
// Method hiding using the 'new' keyword
public new void Display()
{
Console.WriteLine("DerivedClass Display");
}
}
class Program
{
static void Main()
{
BaseClass baseObj = new BaseClass();
baseObj.Display(); // Output: BaseClass Display
DerivedClass derivedObj = new DerivedClass();
derivedObj.Display(); // Output: DerivedClass Display
// Even though the reference is of type BaseClass, it calls the hidden method in the DerivedClass
BaseClass polymorphicObj = new DerivedClass();
polymorphicObj.Display(); // Output: BaseClass Display (due to the 'new' keyword)
}
}
In the example above, the Display method in the DerivedClass hides the Display method in the BaseClass. When the method is called on an object of the derived class, the hidden method in the derived class is executed. However, when the method is called through a base class reference pointing to a derived class object (polymorphism), the base class method is called unless the method is marked with the override keyword.