← Back to C# Course | Chapter 7: Inheritance | Lesson 5 of 6

Sealed Classes

A sealed class is a class that is locked so no one can build on it, like a finished sculpture that cannot be changed. Nothing can inherit from it.

In this page:

  1. Sealed Classes
Syntax
csharp
sealed class ClassName
{
    // cannot be inherited
}

// or seal one method:
// public sealed override void MethodName() { }

Sealed Classes

A sealed class cannot be inherited from at all, preventing any further subclassing. You can also seal an individual override method so deeper subclasses can't override it again.

Sealing is often used for security, performance, or to lock down a design that shouldn't be extended.

Note: Sealing a class can let the compiler apply certain optimizations since the type hierarchy is known to stop there.

Example: Sealed Classes

markup
using System;

sealed class FinalConfig
{
    public string Version = "1.0";

    public void Show()
    {
        Console.WriteLine($"Config version {Version}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        FinalConfig config = new FinalConfig();
        config.Show();
        // class Extended : FinalConfig {} would be a compile error
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to inherit from a sealed class, which is a compile error.
  2. Using sealed on a class that needs to be extended later.
  3. Marking a method sealed without override, which is not allowed.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.