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:
Syntax
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Trying to inherit from a
sealedclass, which is a compile error. - Using
sealedon a class that needs to be extended later. - Marking a method
sealedwithoutoverride, which is not allowed.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: