Understanding Sealed Classes and Sealed Methods in C#

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:

Screenshot taken by author

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?

  • Sealing a class ensures that functionality defined in it cannot be altered by subclassing.
  • Prevents accidental or malicious modifications.
  • Since the compiler knows that a class cannot be inherited, it can optimize method calls for better performance.
  • Clarifies the intent for other developers working with your codebase.


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

Screenshot taken by author

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?

  1. Sealing the method is a good practice if you want to allow subclasses to override a method but prevent further overrides in deeper levels of the inheritance hierarchy.
  2. Sealing a method ensures that its functionality is preserved and that future modifications do not introduce bugs or unexpected behavior.


When to Use Sealed Classes and Sealed Methods

Sealed Class Use Cases:

  • If you want to create a utility class that’s not meant to be extended.
  • If a class contains sensitive logic that should not be altered through inheritance.
  • Performance-critical applications, where sealing a class can yield performance benefits.

Sealed Method Use Cases:

  • You’ve overridden a base class method and want to finalize its implementation to avoid future overrides.
  • The method behavior in your current derived class is considered the optimal or correct implementation, and any further changes could cause instability or bugs.


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:

Screenshot taken by author

Explanation:

  • There is a UserAccount which acts as a base account.
  • There is an AdminAccount that inherits the base class UserAccount.
  • There is another sealed class SuperAdminAccount that contains ResetPassword()`. Notice, this method shows an error when you hover on it

Screenshot taken by author

The error is self explanatory though, but it says you cannot re-implement something that is a sealed one.

  • Furthermore, if there is another class that implements a sealed class, it is not considered valid.

Screenshot taken by author

  • Here, we have ManagerAccount that tries to inherit SuperAdminAccount but has an issue inheriting because it is deriving the sealed class.


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!

要查看或添加评论,请登录

Asp.net with c#的更多文章

社区洞察

其他会员也浏览了