0Pricing
C# Academy · Lesson

virtual/override/sealed; abstract classes

Learn virtual methods, overriding, sealing overrides, and abstract classes; see how base references dispatch to derived implementations.

Inheritance basics

Goal: Reuse and customize behavior through inheritance.

  • virtual in base
  • override in derived
  • sealed override to stop further changes
  • abstract class defines a contract + shared code

virtual + override

virtual enables overriding. Calls through a base reference use the derived override (dynamic dispatch).

using System;

// Base method is virtual so derived classes can customize it
public class Shape
{
  public virtual double Area()
  {
    return 0.0; // default
  }
}

public class Rectangle : Shape
{
  public int Width { get; private set; }
  public int Height { get; private set; }

  public Rectangle(int w, int h)
  {
    Width = w; Height = h;
  }

  public override double Area()
  {
    return Width * Height;
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Shape s = new Shape();
    Shape r = new Rectangle(3, 4); // base reference
    Console.WriteLine("Shape area = " + s.Area());
    Console.WriteLine("Rectangle area = " + r.Area()); // calls Rectangle.Area()
  }
}

All lessons in this course

  1. virtual/override/sealed; abstract classes
  2. Interfaces (intro) & multiple interface implementation
  3. Polymorphism & dynamic dispatch
← Back to C# Academy