Monday, 17 November 2025

Function Overriding in C#

Function Overriding in C#

Function Overriding

Function overriding means defining the same method in a derived class that already exists in the base class, using the same name, parameters, and return type. It is used to change the inherited behavior.

Key Points

  • Requires virtual in the base class.
  • Requires override in the derived class.
  • Method name, parameters, and return type must match exactly.
  • Used for runtime polymorphism.

C# Example:

class Car { public virtual void Drive() { Console.WriteLine("Car is driving."); } } class SportsCar : Car { public override void Drive() { Console.WriteLine("SportsCar is driving very fast!"); } } class Program { static void Main() { Car c = new SportsCar(); c.Drive(); } }

Output:

SportsCar is driving very fast!

No comments:

Post a Comment