How to Resolve Error "CS0239: 'member' : cannot override inherited member 'inherited member' because it is sealed" in C#
The Compiler Error CS0239 is an inheritance restriction error. The message reads: "'ChildClass.Method' : cannot override inherited member 'ParentClass.Method' because it is sealed".
In C#, the sealed keyword is used to stop the chain of inheritance. When applied to a method, property, or event, it signifies that the member is final. The developer of the parent class explicitly decided that no further modifications to this logic should be allowed in subclasses.
This guide explains how sealed works in inheritance chains and how to handle situations where you need to extend a sealed member.
Understanding the Inheritance Chain
To reach this error, you usually have a three-level inheritance hierarchy:
- Level 1 (Base): Defines a
virtualmember. - Level 2 (Parent): Overrides that member and marks it
sealed override. This locks the implementation. - Level 3 (Child): Tries to
overrideit again. CS0239 occurs here.
The sealed modifier effectively says: "The polymorphism stops here."
Scenario: Attempting to Override a Sealed Member
In this example, the Manager class has decided that CalculatePay is final. The Director class tries to change it but is blocked by the compiler.
Example of error:
public class Employee
{
public virtual void CalculatePay() => System.Console.WriteLine("Standard Pay");
}
public class Manager : Employee
{
// The 'sealed' keyword stops future classes from overriding this.
public sealed override void CalculatePay() => System.Console.WriteLine("Manager Pay");
}
public class Director : Manager
{
// ⛔️ Error CS0239: 'Director.CalculatePay()': cannot override inherited member
// 'Manager.CalculatePay()' because it is sealed.
public override void CalculatePay()
{
System.Console.WriteLine("Director Pay");
}
}