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

Method Overriding

Method overriding is when a child class does an inherited job its own way, like a kid who cooks Grandma's recipe with a twist. The parent has to say the method may be changed with the virtual word.

In this page:

  1. Method Overriding
Syntax
csharp
class BaseClass
{
    public virtual ReturnType MethodName() { }
}

class DerivedClass : BaseClass
{
    public override ReturnType MethodName() { }
}

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());
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting virtual in the base method, so override is not allowed.
  2. Forgetting override in the derived method, which creates a hiding warning instead of overriding.
  3. Changing the return type or parameters of an overriding method, which is a compile error.
🔒

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.