The sealed keyword in C# is a powerful construct that is used to restrict inheritance. It prevents other classes from deriving from a class or prevents a method from being overridden further in a derived class. This concept plays a crucial role in enforcing encapsulation, optimizing performance, and securing class designs. In this guide, we will explore the sealed keyword in-depth, examining its use in classes, methods, real-world applications, and best practices.
The sealed keyword can be applied in two primary contexts:
There are several reasons for using the sealed keyword:
When a class is marked as sealed, it cannot be used as a base class. This is useful for utility, helper, or internal classes that should not be extended.
sealed class FinalClass
{
public void Display()
{
Console.WriteLine("This is a sealed class.");
}
}
// This will cause a compile-time error
class DerivedClass : FinalClass
{
}
Trying to inherit from a sealed class will result in a compilation error: "Cannot derive from sealed type 'FinalClass'".
A method can be marked as sealed when it is part of a class hierarchy and has been overridden. Marking a method as sealed ensures that no further overriding can occur beyond the current class.
class Base
{
public virtual void Show()
{
Console.WriteLine("Base implementation");
}
}
class Derived : Base
{
public sealed override void Show()
{
Console.WriteLine("Derived sealed implementation");
}
}
class SubDerived : Derived
{
// Compile-time error: cannot override sealed method
// public override void Show()
// {
// Console.WriteLine("Attempting to override");
// }
}
In this example, the method Show() in the Derived class is sealed and thus cannot be overridden in the SubDerived class.
Sealing a class can protect critical business logic from being altered through inheritance. This ensures that the functionality remains consistent and secure.
Sealed methods are not subject to override, which allows the JIT compiler to optimize the method calls more aggressively through techniques like inlining.
In large frameworks, base classes are often sealed to prevent clients from extending them incorrectly, which could lead to maintenance challenges.
Utility or static classes are often sealed to indicate that they are not intended to be inherited.
sealed class BankTransaction
{
public void ProcessTransaction()
{
Console.WriteLine("Processing transaction securely.");
}
}
By sealing the BankTransaction class, the developer ensures that no other class can alter the logic through inheritance, thus preserving the security and correctness of the implementation.
class Logger
{
public virtual void Log(string message)
{
Console.WriteLine($"Base log: {message}");
}
}
class FileLogger : Logger
{
public sealed override void Log(string message)
{
Console.WriteLine($"File log: {message}");
}
}
Here, the log method in FileLogger is sealed to prevent further customization, which can be important in compliance or audit scenarios.
| Keyword | Description | Can be Inherited? | Can be Overridden? |
|---|---|---|---|
| sealed | Prevents inheritance or overriding | No | No |
| abstract | Must be overridden in derived class | Yes | Must override |
| virtual | May be overridden in derived class | Yes | Optional |
A class marked static is implicitly sealed. You cannot inherit from a static class.
static class Utility
{
public static void DoWork()
{
Console.WriteLine("Work done.");
}
}
Not allowed. You cannot mark a class as both sealed and abstract because it is a contradiction. An abstract class is meant to be extended, while a sealed class cannot be extended.
Many .NET framework classes are sealed. Examples include:
These classes are sealed to prevent modification of core behavior, improve performance, and maintain reliability across the .NET ecosystem.
Sealing methods or classes can provide small performance gains in tight loops or performance-critical applications, because:
Sometimes sealing is confused with access restriction. If you simply want to prevent use outside of an assembly, consider using the internal modifier instead of sealing the class.
internal class InternalClass
{
// Accessible only within the same assembly
}
If a class was sealed but later you decide to allow extension, simply remove the sealed keyword. However, be cautious:
The sealed keyword in C# is a vital part of the languageβs type safety and design principles. It provides developers the ability to finalize class hierarchies or lock down method behavior for security, clarity, and performance. Used correctly, it helps in maintaining strong object-oriented design by explicitly expressing intent and boundaries in your code.
By mastering the use of the sealed keyword, developers can produce safer, more maintainable, and performant code.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved