What is Sealed Class in C#: Definition and Usage
sealed class in C# is a class that cannot be inherited by other classes. It is used to prevent further extension of the class, ensuring its behavior stays unchanged.How It Works
Think of a sealed class like a locked box. Once you seal it, no one can open it to add or change what's inside. In programming, sealing a class means no other class can inherit from it or build upon it.
This is useful when you want to make sure the class's behavior stays exactly as you designed it, without any changes from child classes. It helps keep your code safe and predictable.
In C#, you add the sealed keyword before the class name to lock it down. If someone tries to inherit from a sealed class, the compiler will give an error, stopping them.
Example
This example shows a sealed class called Vehicle. Trying to inherit from it will cause a compile error.
sealed class Vehicle { public void Start() { System.Console.WriteLine("Vehicle started."); } } // This will cause a compile error: // class Car : Vehicle {} class Program { static void Main() { Vehicle v = new Vehicle(); v.Start(); } }
When to Use
Use a sealed class when you want to make sure no one changes or extends your class. This is helpful for security, performance, or design reasons.
For example, if you create a class that handles sensitive data or critical logic, sealing it prevents accidental or harmful changes through inheritance.
Also, sealing classes can improve performance slightly because the runtime knows the class won’t have subclasses.
Key Points
- A sealed class cannot be inherited.
- Use
sealedkeyword before the class name. - Prevents modification of class behavior through inheritance.
- Useful for security, design clarity, and slight performance gains.