Letβs go through sealed
classes and methods in C# β a key feature for controlling inheritance and overriding.
π 1. What Is a sealed
Class?
-
A
sealed
class cannot be inherited. -
Useful when you want to prevent other classes from deriving from it.
-
Often used for security, immutability, or performance reasons.
Example: Sealed Class
sealed class Logger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
// Trying to inherit from Logger will cause a compile-time error
// class FileLogger : Logger {} // β Error
- The compiler will prevent any class from inheriting a sealed class.
π 2. What Is a sealed
Method?
-
A
sealed
method prevents further overriding in derived classes. -
Only makes sense when overriding a virtual method in a class hierarchy.
Syntax Example
class Base
{
public virtual void Display()
{
Console.WriteLine("Base display");
}
}
class Derived : Base
{
public sealed override void Display()
{
Console.WriteLine("Derived display");
}
}
class MoreDerived : Derived
{
// public override void Display() {} // β Error: cannot override sealed method
}
sealed override
stops further overriding beyond the current class.
π 3. Key Points
Feature | Notes |
---|---|
sealed class | Cannot be inherited |
sealed method | Cannot be overridden in derived classes |
Use case | Security, immutability, controlling inheritance |
Relationship | A method can only be sealed if it overrides a virtual method |
π 4. Analogy
-
Sealed class β like a locked box: no one can make a copy of it.
-
Sealed method β like a final lock on a drawer: derived classes canβt change whatβs inside, even if they inherit the box.
β Summary:
-
Use
sealed
classes to prevent inheritance. -
Use
sealed
methods to stop further overriding in a hierarchy. -
Helps enforce design constraints and maintain control over class behavior.
If you want, I can make a diagram showing class hierarchy with sealed classes and sealed methods β it makes the concept visually clear.
Do you want me to make that diagram?