Method Hiding in C#
What is Method Hiding in C#?
Method Hiding in C# allows a derived class to define a method with the same name as a method in its base class, effectively hiding the base class method. Unlike Method Overriding, method hiding does not involve polymorphism.
Key Features of Method Hiding
- Uses the
new
keyword to hide the base class method. - The base class method is still accessible through base class references.
- Does not support runtime polymorphism.
- Can be useful when a derived class needs a completely different implementation.
Example of Method Hiding
The following example demonstrates how method hiding works using the new
keyword.
Example of Method Hiding:
public class BaseClass
{
public void Show()
{
Console.WriteLine("Base class Show method.");
}
}
public class DerivedClass : BaseClass
{
public new void Show()
{
Console.WriteLine("Derived class Show method.");
}
}
// Usage
BaseClass baseObj = new BaseClass();
baseObj.Show(); // Output: Base class Show method.
DerivedClass derivedObj = new DerivedClass();
derivedObj.Show(); // Output: Derived class Show method.
BaseClass refObj = new DerivedClass();
refObj.Show(); // Output: Base class Show method.
In this example, the Show()
method in the derived class hides the base class method. However, when accessed via a base class reference, the base method is called.
Method Hiding vs. Method Overriding
While both techniques allow a derived class to redefine methods from a base class, they have key differences.
Feature | Method Hiding | Method Overriding |
---|---|---|
Keyword Used | new |
override |
Base Method Requirement | Can be any method (not necessarily virtual or abstract). | Must be marked as virtual , abstract , or override in the base class. |
Polymorphism | Does not support runtime polymorphism. | Supports runtime polymorphism. |
Base Method Accessibility | Base method can still be accessed through base class reference. | Derived class method completely replaces the base method. |
Accessing Hidden Methods Using Base Keyword
Even if a method is hidden in the derived class, it can still be accessed using the base
keyword.
Example of Accessing Hidden Methods:
public class Parent
{
public void Display()
{
Console.WriteLine("Parent class Display method.");
}
}
public class Child : Parent
{
public new void Display()
{
base.Display(); // Calls base class method
Console.WriteLine("Child class Display method.");
}
}
// Usage
Child obj = new Child();
obj.Display();
// Output:
// Parent class Display method.
// Child class Display method.
Here, base.Display()
allows the derived class to call the hidden method from the base class.
When to Use Method Hiding?
- When a derived class needs a completely different implementation.
- When base class functionality should still be accessible.
- When the base method is not
virtual
orabstract
, preventing overriding.