Method Hiding in C#
What is Method Hiding?
Method hiding in C# occurs when a derived class declares a method that hides an inherited method from the base class. Method hiding is achieved using the new
keyword. It allows the derived class to provide its own implementation while "hiding" the base class version.
Why Use Method Hiding?
Method hiding allows developers to redefine base class methods in the derived class. Unlike method overriding, method hiding does not replace the base class method but hides it when accessed via a derived class instance.
Example: Method Hiding in C#
Below is an example demonstrating method hiding. The Vehicle
class has a DisplayInfo
method, and the Car
class hides this method using the new
keyword.
Example Code:
public class Vehicle
{
public void DisplayInfo()
{
Console.WriteLine("This is a vehicle.");
}
}
public class Car : Vehicle
{
// Method hiding using the 'new' keyword
public new void DisplayInfo()
{
Console.WriteLine("This is a car.");
}
}
// Usage
Vehicle vehicle = new Vehicle();
vehicle.DisplayInfo(); // Output: This is a vehicle.
Car car = new Car();
car.DisplayInfo(); // Output: This is a car.
Vehicle vehicleAsCar = new Car();
vehicleAsCar.DisplayInfo(); // Output: This is a vehicle (base class method is called)
In this example, the DisplayInfo
method is hidden in the derived class Car
using the new
keyword. When the DisplayInfo
method is called via the base class reference, the base class version of the method is invoked.
Key Characteristics of Method Hiding
- Method hiding uses the
new
keyword to hide the base class method in the derived class. - If a method is hidden in a derived class, the base class version is still accessible through a base class reference.
- Unlike method overriding, method hiding does not require the base class method to be marked as
virtual
.
Method Hiding vs. Method Overriding
Method hiding and method overriding allow derived classes to modify behavior from base classes, but they differ in their execution:
- Method Hiding: Uses the
new
keyword to hide the base class method. The base class method can still be accessed using a base class reference. - Method Overriding: Uses the
override
keyword to replace the base class method. The base class method cannot be accessed from a derived class instance.
Rules for Method Hiding
- The
new
keyword must be used to hide a base class method in the derived class. - The method signature in the derived class must match the base class method.
- The base class method is still accessible when using a base class reference, even if it’s hidden in the derived class.
Key Points to Remember
- Method hiding allows a derived class to hide an inherited method from the base class using the
new
keyword. - The hidden method in the base class can still be accessed via a base class reference.
- Method hiding is different from method overriding, where the base class method is replaced.