The sealed keyword in C# is a modifier that prevents further inheritance of a class or overrides of a method.
- For Classes: When applied to a class, it prevents that class from being used as a base class.
- For Methods: When applied to a method, it prevents that method from being overridden in any derived classes.
Why use sealed?
There are several reasons one might opt to use the sealed keyword:
- Intention Clarification: It makes your intention clear that a class or method shouldn’t be extended or overridden.
- Avoid Unintended Inheritance: It helps in preventing other developers from mistakenly extending or modifying the behavior of your class or method.
- Performance: Some run-time optimizations can be made by the JIT compiler when it knows a class or method won’t be extended or overridden.
Using sealed with Classes:
To seal a class, you simply add the sealed keyword before the class declaration:
public sealed class MySealedClass
{
// Class members go here
}
By doing this, any attempt to inherit from MySealedClass will result in a compile-time error.
Using sealed with Methods:
In the context of methods, the sealed keyword is used to prevent further overrides of a method in a derived class. Note that a method must be marked as override to be sealed:
public class BaseClass
{
public virtual void MyMethod()
{
// Some logic
}
}
public class DerivedClass : BaseClass
{
public sealed override void MyMethod()
{
// New logic
}
}
Any further attempts to override MyMethod in classes derived from DerivedClass will cause a compile-time error.
Points to Remember:
- You can’t mark a method with
sealedunless it’s also marked withoverride. - Structs cannot be sealed because they don’t support inheritance.
- Sealed classes cannot be abstract.
Conclusion:
The sealed keyword in C# provides a way to protect your classes and methods from unintended inheritance and overriding. Whether you’re aiming for design clarity, prevention of potential future errors, or optimization, the sealed keyword is an essential tool in a C# developer’s toolbox.
Leave a comment