← Back to C# Course | Chapter 7: Inheritance | Lesson 3 of 6

Method Overriding

In this page:

  1. Method Overriding

Method Overriding

A base class marks a method virtual to allow derived classes to replace its behavior with override. At runtime, C# calls the overridden version based on the object's actual type, not the variable's declared type — this is polymorphism. Without virtual/override, a derived method with the same name just hides the base one instead.

Warning: Forgetting virtual on the base method means override in the derived class will not compile.

Example: Method Overriding

markup
using System;

class Shape
{
    public virtual double Area()
    {
        return 0;
    }
}

class Circle : Shape
{
    public double Radius;

    public Circle(double radius)
    {
        Radius = radius;
    }

    public override double Area()
    {
        return Math.PI * Radius * Radius;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Shape s = new Circle(3);
        Console.WriteLine(s.Area());
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.