Understanding Sealed Classes and Sealed Methods in C#
Providing a robust, modular and maintainable code is the specialty of C# in OOP concept. There are two further concepts in C# that enhances the security and performances to your code — Sealed classes and Sealed methods.
Let’s dive into what sealed classes and sealed methods are, how they work, and why you would use them.
Sealed class
In C#, if you want to protect your class from inheritance for some reason, you would use Sealed class. In other words, This is a special class that cannot be inherited by other classes.
Syntax
sealed class MySealedClass
{
// Class implementation
}
Let’s take a look at the example to understand this in a better way:
In this example, as you can see there is a PaymentProcessor class that is sealed, meaning no class can derive from it. If you attempt to inherit from a sealed class, the compiler will throw an error.
Why Use a Sealed class?
Sealed Method
In C#, there is a provision to override the default implementation and provide each methods with their own implementation. This can be achieved via virtual and override. This is basically called overriding. But what if you want to prevent method from overriding? — That’s where sealed classes come to the rescue! Once a method is marked sealed, any further derived classes cannot override it.
However, a method can only be sealed if it is an overridden method. You cannot directly seal a method unless it is part of an inheritance chain.
Syntax
public override sealed void MyMethod()
{
// Method implementation
}
Example
In this example, the Display method in DerivedClass is marked as sealed. As a result, FurtherDerivedClass is not allowed to override the Display method. Attempting to override the method in FurtherDerivedClass results in a compile-time error.
Why Use a Sealed Method?
领英推荐
When to Use Sealed Classes and Sealed Methods
Sealed Class Use Cases:
Sealed Method Use Cases:
Practical Example of Sealed Classes and Methods
Let’s look at a more concrete example combining sealed classes and methods in a real-world context:
Explanation:
The error is self explanatory though, but it says you cannot re-implement something that is a sealed one.
Conclusion
Sealed classes and sealed methods in C# provide developers with the tools to control inheritance, secure class functionality, and optimize performance. By using them judiciously, you can enforce better design practices, ensure that critical functionality is not inadvertently altered, and in some cases, improve the performance of your applications.
Sealing classes and methods is an important part of understanding how C# supports safe and efficient object-oriented programming.
Like it?
Please don’t forget to like this post if you find it useful. Also, if you can, a comment will be appreciated to keep me writing such posts and boost my confidence further! ??
Thank you for reading!