Method Overriding in C#: Definition and Example
method overriding allows a subclass to provide a specific implementation of a method that is already defined in its base class. It uses the virtual keyword in the base class and the override keyword in the subclass to replace the base method behavior.How It Works
Method overriding in C# works like a child changing the way a parent’s instruction is followed. Imagine a parent gives a general rule, but the child wants to do it in their own style. The base class defines a method as virtual, which means it can be changed later. The subclass then uses override to provide its own version of that method.
When you call the method on an object, C# checks the actual type of the object at runtime and runs the overridden method if it exists. This is called runtime polymorphism. It helps programs be flexible and extendable, letting subclasses customize behavior without changing the base class.
Example
This example shows a base class Animal with a virtual method Speak. The subclass Dog overrides Speak to provide its own message.
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(); // Calls base method Dog myDog = new Dog(); myDog.Speak(); // Calls overridden method Animal animalDog = new Dog(); animalDog.Speak(); // Calls overridden method because of runtime type } }
When to Use
Use method overriding when you want to change or extend the behavior of a method defined in a base class without modifying the base class itself. This is common in situations where you have a general class and more specific subclasses that need to behave differently.
For example, in a game, you might have a base class Character with a method Attack. Different character types like Wizard or Warrior can override Attack to perform unique actions. This keeps your code organized and easy to maintain.
Key Points
- Method overriding requires the base method to be marked
virtualorabstract. - The subclass method must use the
overridekeyword. - Overriding enables runtime polymorphism, allowing the program to decide which method to call based on the object type.
- It helps customize or extend base class behavior safely.