Method hiding in C# occurs when a derived class defines a method with the same name and signature as a method in its base class but does not use the override keyword. Instead, the new keyword is used to hide the base class method. This is different from method overriding, where the derived class provides a new implementation for a base class method using the override keyword. Method hiding allows the derived class to define a method that hides the implementation of the base class method without overriding it.
Basics of Method Hiding
To hide a method in C#, you use the new keyword in the derived class’s method definition. This tells the compiler that the derived class method is intended to hide the base class method.
Example
usingSystem;
classAnimal { // Base class method publicvoidSpeak() { Console.WriteLine("The animal makes a sound."); } }
classDog : Animal { // Derived class method hiding the base class method publicnewvoidSpeak() { Console.WriteLine("The dog barks."); } }
classProgram { staticvoidMain() {
// Creating an instance of the base class AnimalgenericAnimal=newAnimal(); genericAnimal.Speak(); // Outputs: The animal makes a sound.
// Creating an instance of the derived class DogspecificDog=newDog(); specificDog.Speak(); // Outputs: The dog barks.
// Demonstrating method hiding AnimalpolymorphicDog=newDog(); polymorphicDog.Speak(); // Outputs: The animal makes a sound. } }
Explanation of the Example
Base Class (Animal):
The Animal class has a method Speak that prints “The animal makes a sound.”
Derived Class (Dog):
The Dog class inherits from Animal and defines a method Speak with the same signature. The new keyword is used to indicate that this method hides the base class method.
Main Method:
We create an instance of Animal and call the Speak method, which prints “The animal makes a sound.”
We create an instance of Dog and call the Speak method, which prints “The dog barks.”
We create an Animal reference that points to a Dog object and call the Speak method. This demonstrates method hiding, as it calls the base class method, printing “The animal makes a sound.”
Key Points About Method Hiding
Use of new Keyword:
The new keyword is used to hide the base class method. It informs the compiler that the derived class method is intended to hide the inherited method.
Method Hiding vs. Overriding:
Method hiding and method overriding are different. Method overriding uses the override keyword and maintains polymorphic behavior, while method hiding uses the new keyword and does not.
Accessing Hidden Methods:
To call the hidden base class method from a derived class instance, you need to cast the instance to the base class type.