Summary: in this tutorial, you’ll learn how to use the C# sealed modifier to prevent a class from inheriting by other classes or a class member from overriding by a member in the subclass.
Introduction to the C# sealed modifier
When creating a class, you should consider the following points:
- The benefits that other classes may gain by inheriting from your class.
- The side effects if other classes extend your class in such as way that it would no longer work correctly or as expected.
If the second point is obvious, you can prevent it by using the C# sealed
modifier.
When you apply the sealed
modifier to a class, you prevent other classes from inheriting it:
sealed class MyClass
{
}
Code language: C# (cs)
In this example, we use the sealed
modifier for the MyClass
so that other classes cannot inherit from it. If you attempt to subclass the MyClass
, you’ll get an error. For example:
class MySubclass: MyClass
{
}
Code language: C# (cs)
Error:
'MySubclass': cannot derive from sealed type 'MyClass'
Code language: C# (cs)
Also, you can apply the sealed
modifier to a property or method that overrides a virtual property or method. The sealed properties and methods seal their implementations to prevent overriding. For example:
class MyClass
{
public virtual string Name { get; set; }
public virtual void MyMethod() { }
}
class Subclass : MyClass
{
public sealed override string Name { get; set; }
public sealed override void MyMethod() { }
}
Code language: C# (cs)
In this example, the subclasses of the MySubclass
cannot override the Name
property and MyMethod
method.
Summary
- Use the
sealed
modifier for a class to prevent it from being subclassed by other classes. - Use the
sealed
modifier for a property or a method to prevent it from being overridden by the members in the subclasses.