C# tutorials > Core C# Fundamentals > Object-Oriented Programming (OOP) > What are sealed classes?
What are sealed classes?
Understanding Sealed Classes in C#
In C#, a sealed class is a class that cannot be inherited. This means that no other class can derive from it. The sealed
keyword prevents inheritance, providing a way to control the class hierarchy and prevent unintended modifications or extensions. This tutorial explains the concept of sealed classes with code examples and practical considerations.
Basic Definition
Declaring a class as sealed
is straightforward. Just add the sealed
keyword before the class
keyword in its declaration. In this example, MySealedClass
is marked as sealed, preventing any other class from inheriting from it.
sealed class MySealedClass
{
public string Message { get; set; }
public MySealedClass(string message)
{
Message = message;
}
public void DisplayMessage()
{
Console.WriteLine(Message);
}
}
Compilation Error Demonstration
If you attempt to inherit from a sealed class, the C# compiler will throw an error indicating that you cannot derive from a sealed type. The commented-out code demonstrates the attempt to inherit from MySealedClass
, which is sealed, leading to a compilation error.
// Compilation error: Cannot derive from sealed type 'MySealedClass'
//class MyDerivedClass : MySealedClass
//{
//
//}
Concepts Behind the Snippet
The primary concept behind sealed classes is to prevent inheritance. This is useful when you want to ensure that the behavior of a class remains consistent and predictable, without the risk of modifications through inheritance. Sealing a class can provide performance benefits, because the compiler can optimize calls to virtual members since it knows that the method will not be overridden in a derived class.
Real-Life Use Case Section
Sealed classes are often used for utility classes that provide static helper methods. In this example, StringHelper
is a sealed class that offers a static method for reversing strings. Sealing ensures that no other class can inherit from StringHelper
and potentially modify its behavior.
// Utility class with static helper methods
sealed class StringHelper
{
public static string ReverseString(string input)
{
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
Best Practices
Use sealed classes when you want to prevent inheritance to maintain the integrity and behavior of a class. Consider sealing a class when you are confident that no further specialization or modification is needed through inheritance. Avoid sealing classes prematurely, as it can limit extensibility in the future. Document why a class is sealed to inform other developers of the design decision.
Interview Tip
When discussing sealed classes in an interview, emphasize their role in preventing inheritance and maintaining class integrity. Explain the benefits of using sealed classes, such as performance optimizations and preventing unintended modifications. Be prepared to discuss scenarios where sealed classes are appropriate and scenarios where they should be avoided.
When to Use Them
Use sealed classes in the following scenarios: When you want to prevent inheritance to ensure the integrity and behavior of a class. When you are creating utility classes with static helper methods. When you want to optimize performance by preventing virtual method calls from being overridden. When you are confident that no further specialization or modification is needed through inheritance. When creating data transfer objects(DTOs).
Memory footprint
Sealed classes do not directly affect the memory footprint of an application. The memory footprint is determined by the objects created from the class, not the class itself. However, sealed classes can indirectly improve performance by allowing the compiler to optimize virtual method calls, potentially reducing the execution time and memory usage.
Alternatives
If you need to prevent inheritance but still want to allow some level of customization, consider using interfaces or abstract classes. Interfaces define a contract that classes can implement, providing a way to enforce specific behaviors. Abstract classes can provide a base implementation while allowing derived classes to override specific methods. Another alternative is composition, where you include instances of other classes as members instead of inheriting from them.
Pros
Cons
FAQ
-
Can I seal a method in a sealed class?
Yes, you can seal a method in a sealed class, but it is redundant since the class itself cannot be inherited, so the method effectively cannot be overridden anyway. Sealing a method in a sealed class doesn't provide any additional protection or behavior. -
Are sealed classes applicable to structs in C#?
No, sealed classes are not applicable to structs in C#. Structs are value types and are implicitly sealed. They cannot be inherited or derived from, so thesealed
keyword is not allowed for structs. -
Can I use sealed classes with interfaces?
No, you cannot directly use sealed classes with interfaces. Interfaces define a contract that classes can implement, but they do not inherit from each other. Sealed classes prevent inheritance, which is a different concept from implementing interfaces.