A sealed class is a class in C# that cannot be inherited by other classes. This type of class is used when we want to protect the design of a class and prevent other classes from inheriting from it, keeping the implementation of the sealed class secure and unmodified.
Sealed classes are useful in situations where we need to limit the extensions of a class or when a class has been optimized to fulfill a specific function and does not need to be extended.
Basic syntax of a sealed class
To define a sealed class in C#, we use the sealed
keyword before class
. Let’s see a basic example:
public sealed class MyClass
{
public void Method()
{
Console.WriteLine("This is a method of a sealed class.");
}
}
In this example, Calculator
is a sealed class that provides methods for performing basic addition and subtraction operations. Being sealed, it cannot be inherited from.
Using sealed classes in practice
Consider the following scenario: suppose we are creating an authentication system. We could have a sealed class that handles the authentication logic.
If inheritance were allowed, other developers could create subclasses that alter this behavior, which could introduce vulnerabilities.
public sealed class Authentication
{
public bool ValidateUser(string username, string password)
{
// Validation logic
return (username == "admin" && password == "1234");
}
}
In this example, the Authentication
class is sealed, which means that no one can inherit from it and modify the validation logic.