Method Overriding in C#
What is Method Overriding in C#?
Method Overriding is a feature in C# that allows a derived class to provide a specific implementation of a method that is already defined in its base class. It is a key concept of runtime polymorphism.
Key Features of Method Overriding
- Requires a base class method to be marked as
virtual
orabstract
. - The derived class method must have the same signature and use the
override
keyword. - Supports runtime polymorphism by determining which method to call at runtime.
- Provides flexibility by allowing derived classes to customize base class behavior.
Example of Method Overriding
The following example demonstrates how method overriding works.
Example of Method Overriding:
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound.");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog barks.");
}
}
// Usage
Animal myAnimal = new Dog();
myAnimal.MakeSound(); // Output: Dog barks.
In this example, the MakeSound()
method in the Dog
class overrides the same method in the Animal
class.
Method Overriding vs. Method Hiding
C# allows both method overriding and method hiding. The difference is:
Feature | Method Overriding | Method Hiding |
---|---|---|
Keyword Used | override in the derived class. |
new in the derived class. |
Base Method | Must be marked as virtual or abstract . |
Does not need to be virtual or abstract. |
Behavior | Allows derived class to customize base class behavior. | Hides the base class method instead of overriding it. |
Accessing Base Method | Use base.MethodName() to call the base method. |
Base class method remains accessible via casting. |
Example of Method Hiding
Below is an example where a method is hidden rather than overridden:
Example of Method Hiding:
public class Animal
{
public void MakeSound()
{
Console.WriteLine("Animal makes a sound.");
}
}
public class Dog : Animal
{
public new void MakeSound()
{
Console.WriteLine("Dog barks.");
}
}
// Usage
Animal myAnimal = new Dog();
myAnimal.MakeSound(); // Output: Animal makes a sound
Dog myDog = new Dog();
myDog.MakeSound(); // Output: Dog barks.
In this example, the new
keyword hides the MakeSound()
method of the base class instead of overriding it.
Rules for Method Overriding
- The base class method must be marked as
virtual
orabstract
. - The overriding method in the derived class must have the same name, return type, and parameters.
- The derived class method must be marked with the
override
keyword. - Method overriding supports runtime polymorphism.
Benefits of Method Overriding
- Allows a derived class to provide a custom implementation of a base class method.
- Enables runtime polymorphism for flexible and reusable code.
- Improves maintainability by promoting modular code.
- Supports OOP principles by enhancing inheritance.