C# `sealed` Keyword: Preventing Inheritance and Overriding

Learn how to use the `sealed` keyword in C# to prevent inheritance and method overriding. This tutorial explains its application to classes and methods, demonstrating how `sealed` enhances code control, improves performance, and helps maintain consistent class behavior across inheritance hierarchies.



Understanding the `sealed` Keyword in C#

What Does `sealed` Do?

In C#, the `sealed` keyword is used to prevent inheritance and overriding. Applying `sealed` to a class means that class cannot be inherited from (no other classes can be derived from it). Applying `sealed` to a method within a class means that method cannot be overridden by derived classes. Structs in C# are implicitly sealed; they cannot be inherited.

`sealed` Classes

A `sealed` class cannot serve as a base class for inheritance. This is useful when you want to explicitly prevent a class from being extended.

Example C# Code (Sealed Class)

public sealed class Animal {
    public void Eat() { Console.WriteLine("Eating..."); }
}

//This will cause a compile-time error because Animal is sealed
public class Dog : Animal { } 

`sealed` Methods

A `sealed` method cannot be overridden in derived classes. It must be declared as `virtual` or `abstract` in the base class, and then the `sealed` keyword must be used in the derived class to prevent further overriding. This is often used to optimize performance or to prevent unintended modification of the base class method in derived classes.

Example C# Code (Sealed Method)

public class Animal {
    public virtual void Run() { Console.WriteLine("Running..."); }
}

public class Dog : Animal {
    public sealed override void Run() { Console.WriteLine("Running fast..."); }
}

//This will cause a compile-time error because Run() is sealed in the Dog class
public class Puppy : Dog {
    public override void Run() { Console.WriteLine("Running slowly..."); }
}

Important Note About `sealed`

The `sealed` keyword cannot be applied to local variables.

Conclusion

The `sealed` keyword in C# is a powerful tool for controlling inheritance and method overriding. It's used to prevent unintended modifications and enhance code predictability and maintainability.