What is method hiding?
Method hiding is a concept in C# where a child class introduces a new method with the same name and signature as a method in its parent class, effectively "hiding" the parent class's method. For this in object oriented programming we use the 'new' keyword to hide a base class member. This new method in the child class is not related to method overriding and doesn't participate in polymorphism like overridden methods do. Instead, it creates a new method in the child class that has the same name as the method in the parent class.
Here's an example of method hiding in C#:
using System;
class Parent {
public void PrintMessage() {
Console.WriteLine("This is the Parent class.");
}
}
class Child : Parent {
public new void PrintMessage() {
Console.WriteLine("This is the Child class.");
}
}
class Program {
static void Main(string[] args) {
Parent parent = new Parent();
Child child = new Child();
parent.PrintMessage(); // Output: This is the Parent class.
child.PrintMessage(); // Output: This is the Child class.
// Using the base class reference to call the parent class method
Parent childAsParent = new Child();
childAsParent.PrintMessage(); // Output: This is the Parent class.
}
}
In this example:
-
The 'Parent' class defines a method named 'PrintMessage'.
- The 'Child' class inherits from 'Parent' and introduces a new method also named 'PrintMessage' by using 'new' keyword. This new method hides the method from the parent class.
- In the 'Main' method, instances of both 'Parent' and 'Child' classes are created. When calling 'PrintMessage', the behavior depends on the type of the instance.
- When using a 'Parent' class reference, the method from the parent class is called.
- When using a 'Child' class reference, the method from the child class is called.
- When using a 'Parent' class reference to point to a 'Child' instance, the method from the parent class is called because method hiding is not related to polymorphism.
Method hiding can lead to confusion and unexpected behavior, so it's generally recommended to use method overriding (with 'virtual' and 'override' keywords) and polymorphism when you want to provide new implementations for methods in derived classes.
Note: You can re-implement a method from the parent class in the child class using two different ways:
1. Method overriding
2. By using new() Keyword