C sharp - Method Overriding in C#
Definition:
Method overriding in C# allows a derived class to provide a new implementation of a method that is already defined in its base class.
This is used when you want to change or extend the behavior of a method inherited from a parent class.
-
The base class method must be marked with the
**virtual**
keyword. -
The derived class must use the
**override**
keyword to override the method. -
It enables runtime polymorphism (method behavior decided at runtime).
Why Use It?
To allow subclasses to define their own version of a method while maintaining the same method name and signature.
using System;
class Animal
{
public virtual void Speak()
{
Console.WriteLine("The animal makes a sound.");
}
}
class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("The dog barks.");
}
}
class Program
{
static void Main()
{
Animal myAnimal = new Animal();
myAnimal.Speak(); // Output: The animal makes a sound.
Dog myDog = new Dog();
myDog.Speak(); // Output: The dog barks.
Animal anotherDog = new Dog();
anotherDog.Speak(); // Output: The dog barks. (Polymorphism)
}
}