Method Overriding
In this page:
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
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());
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: