CSharp - Class and Method Sealing

Introduction

An overridden function member may seal its implementation using sealed keyword to prevent it from being overridden.

The following code seals Square's implementation of Thickness, preventing a class that derives from Square from overriding 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 sealed override decimal Thickness { 
           get { return Width; } 
        }
}

You can seal the class itself which means seals all the virtual functions.

Related Topics

Quiz