CSharp - Inheritance base Keyword

Introduction

base keyword has two usages:

  • Access an overridden function member from the subclass
  • Call a base-class constructor

In this example, Square uses the base keyword to access Shape's implementation of Thickness:

abstract class Shape{
       // Note empty implementation
       public abstract decimal NetValue { get; }
}
class Circle : Shape{
       public long Radius;
       public virtual decimal Thickness => 0;   // Expression-bodied property       
}
class Square : Shape{
       public decimal Width;
       public override decimal Thickness => base.Thickness + Width;
}

With the base keyword, we access Shape's Thickness property non virtually.

The same approach works if Thickness is hidden rather than overridden.

Related Topics