C#  

Understanding Sealed Classes in C# with Example

In C#, sealed classes play an important role in object-oriented design by preventing inheritance. When you mark a class as sealed, you’re telling the compiler (and other developers) that this class cannot be used as a base class.

This is useful for,

  • Enforcing design constraints.
  • Improving performance (in some cases).
  • Preventing misuse of certain classes.

What is a Sealed Class in C#?

A sealed class is a class that cannot be inherited. It is declared using the sealed keyword.

sealed class MyClass
{
    public void Display()
    {
        Console.WriteLine("This is a sealed class.");
    }
}

Trying to inherit from this class will result in a compile-time error:

class Derived : MyClass // ❌ Error: cannot derive from sealed type
{
}

When to Use Sealed Classes?

You might want to use sealed in these situations.

  • To prevent unintended inheritance.
  • To protect sensitive behavior from being overridden.
  • To optimize performance in certain scenarios (because method calls to sealed classes can sometimes be optimized by the JIT compiler).

Example: Sealing a Class

using System;

sealed class Logger
{
    public void Log(string message)
    {
        Console.WriteLine($"Log: {message}");
    }
}
// Attempting to inherit this will result in a compile-time error
// class FileLogger : Logger {} // ❌ Not allowed

class Program
{
    static void Main()
    {
        Logger logger = new Logger();
        logger.Log("Application started.");
    }
}

Sealing a Method

You can also seal a method in a derived class to prevent further overriding. This only makes sense in a class that is already overriding a method from its base class.

class Base
{
    public virtual void Show() => Console.WriteLine("Base Show");
}

class Derived : Base
{
    public sealed override void Show() => Console.WriteLine("Derived Show");
}

// The following would cause a compile-time error
// class SubDerived : Derived
// {
//     public override void Show() {} // ❌ Cannot override sealed method
// }

Sealed Class vs Abstract Class

Feature Sealed Class Abstract Class
Can be inherited ❌ No ✅ Yes
Can be instantiated ✅ Yes ❌ No
Use case Lockdown behavior Provide base functionality
Modifier sealed abstract

Summary

  • A sealed class in C# cannot be inherited.
  • It’s useful for protecting class logic, improving performance, and enforcing strict designs.
  • You can also seal methods in a class to prevent further overrides.

Keywords: sealed, inheritance, override, class design.