Sealed Classes in C#
What are Sealed Classes in C#?
A sealed class in C# is a class that cannot be inherited. It is used to restrict further extension of the class to maintain security and prevent unintended modifications.
Key Features of Sealed Classes
- Prevents inheritance by derived classes.
- Improves performance by allowing compiler optimizations.
- Ensures security by preventing modification of behavior.
- Cannot act as a base class for other classes.
Example of a Sealed Class
The following example demonstrates how a sealed class is declared and used.
Example: Declaring and Using a Sealed Class
sealed class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
// This will cause an error
// class AdvancedCalculator : Calculator { } // Error: Cannot inherit from sealed class
// Usage
Calculator calc = new Calculator();
Console.WriteLine(calc.Add(5, 10)); // Output: 15
In this example, the Calculator
class is marked as sealed
, preventing it from being inherited.
Sealed Methods
In C#, you can use the sealed
keyword on methods inside a base class to prevent them from being overridden in derived classes.
Example: Sealing a Method
public class BaseClass
{
public virtual void Show()
{
Console.WriteLine("Base class method.");
}
}
public class DerivedClass : BaseClass
{
public sealed override void Show()
{
Console.WriteLine("Sealed method in derived class.");
}
}
public class SubDerivedClass : DerivedClass
{
// Cannot override Show() because it is sealed in DerivedClass
// public override void Show() { } // Error
}
// Usage
DerivedClass obj = new DerivedClass();
obj.Show(); // Output: Sealed method in derived class.
Here, the method Show()
is sealed in DerivedClass
, preventing further overrides in SubDerivedClass
.
When to Use Sealed Classes?
- When you want to prevent inheritance to maintain class integrity.
- To improve performance by allowing compiler optimizations.
- When a class is designed to be self-contained without needing extension.
Sealed Classes vs. Abstract Classes
Both sealed and abstract classes control inheritance, but they serve different purposes.
Feature | Sealed Classes | Abstract Classes |
---|---|---|
Inheritance | Cannot be inherited. | Must be inherited; cannot be instantiated. |
Purpose | Prevents modifications to class behavior. | Acts as a blueprint for derived classes. |
Method Behavior | Can have regular methods but cannot be overridden. | Can have abstract and concrete methods. |
Usage | When extension of the class is unnecessary. | When you need base functionality for derived classes. |