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

FeatureNotes
sealed classCannot be inherited
sealed methodCannot be overridden in derived classes
Use caseSecurity, immutability, controlling inheritance
RelationshipA 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?