SyntaxStudy
Sign Up
C# Inheritance and Polymorphism
C# Beginner 1 min read

Inheritance and Polymorphism

C# supports single-class inheritance. A derived class inherits all non-private members of its base class and can override virtual methods to provide specialised behaviour. The `override` keyword is required when overriding a `virtual` or `abstract` method, preventing accidental overrides. Abstract classes cannot be instantiated and may contain abstract members (no body) that derived classes must implement. Sealed classes cannot be subclassed, and sealed methods prevent further overriding in the class hierarchy. These modifiers help API designers communicate intent. Polymorphism allows code to operate on a base type reference while the runtime dispatches to the most-derived implementation. This is the foundation of the Open/Closed Principle: code is open for extension (add a new derived class) but closed for modification (no changes to calling code needed).
Example
// Inheritance, abstract classes, virtual dispatch

public abstract class Shape
{
    public string Color { get; set; } = "Black";
    public abstract double Area();              // must be overridden
    public virtual  string Describe() =>        // can be overridden
        $"{GetType().Name} (color={Color}, area={Area():F2})";
}

public class Circle : Shape
{
    public double Radius { get; }
    public Circle(double radius) => Radius = radius;
    public override double Area() => Math.PI * Radius * Radius;
}

public class Rectangle : Shape
{
    public double Width  { get; }
    public double Height { get; }
    public Rectangle(double w, double h) { Width = w; Height = h; }
    public override double Area() => Width * Height;
    public override string Describe() =>
        base.Describe() + $" [{Width}x{Height}]";
}

// Sealed — no further subclassing allowed
public sealed class Square : Rectangle
{
    public Square(double side) : base(side, side) { }
}

// Polymorphic usage
List<Shape> shapes = new()
{
    new Circle(5)    { Color = "Red"  },
    new Rectangle(4, 6) { Color = "Blue" },
    new Square(3)   { Color = "Green" }
};

foreach (var shape in shapes)
    Console.WriteLine(shape.Describe());

double totalArea = shapes.Sum(s => s.Area());
Console.WriteLine($"Total area: {totalArea:F2}");