25 Feb 2024
Method overriding in C# is a concept of object-oriented programming where a derived class provides a specific implementation for a method that is already defined in its base class, allowing for the same method name to exhibit different behaviors in the base and derived classes. This enables dynamic polymorphism, as the appropriate method to execute is determined at runtime based on the actual type of the object.
In C#, method overriding is accomplished by declaring a method in a derived class with the same signature (method name, parameters, and return type) as a method in its base class. By doing so, the method in the derived class overrides the implementation of the method in the base class.
Example to illustrate method overriding in C#:
using System;
// Base class
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
// Derived class
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
class Program
{
static void Main(string[] args)
{
Shape shape = new Shape();
shape.Draw(); // Output: Drawing a shape
Shape circle = new Circle();
circle.Draw(); // Output: Drawing a circle
}
}
In this example, the Shape class has a virtual method Draw(), which can be overridden by subclasses. The Circle class inherits from Shape and provides its own implementation of the Draw() method. When we create an instance of Circle and call the Draw() method, the overridden implementation in the Circle class is invoked instead of the one in the Shape class. This behavior is known as method overriding or dynamic polymorphism because the actual method implementation is resolved dynamically at runtime based on the object's type.