CSharp - Virtual Function Members


A function marked as virtual can be overridden by subclasses.

Methods, properties, indexers, and events can be virtual.

class Shape
       public string Name;
       public virtual decimal Thickness => 0;   // Expression-bodied property

(Thickness => 0 is a shortcut for { get { return 0; } }.

A subclass overrides a virtual method by applying the override modifier:

class Circle : Shape
       public long Radius;

class Square : Shape
       public decimal Width;
       public override decimal Thickness => Width;

By default, the Thickness of an Shape is 0.

A Circle does not need to specialize this behavior.

Square specializes the Thickness property to return the value of the Width:

Square mySquare = new Square { Name="McMySquare", Width=250000 };
Shape a = mySquare;
Console.WriteLine (mySquare.Thickness);  // 250000
Console.WriteLine (a.Thickness);         // 250000

The signatures, return types, and accessibility of the virtual and overridden methods must be identical.

An overridden method can call its base class implementation via the base keyword.