Sealed keyword as the name suggests seals the entity to which it is applied. Here in this article we will take classes and methods into consideration.
Sealed Keyword with Classes
When sealed keyword is applied to a class, then that class cannot be inherited by any child class in future.
In short, it means sealed class cannot be inherited. Let’s see an example for the same.
We will create two classes ClassA and ClassB. ClassB will inherit from ClassA.
- public class ClassA
- {
- public void MethodA()
- {
- }
- }
-
- public class ClassB : ClassA
- {
- public virtual void Method1()
- {
- }
- }
The above code works perfectly and no error is generated at compile time. Now apply sealed keyword to ClassA and see how things changes:
- sealed public class ClassA
- {
- public void MethodA()
- {
- }
- }
-
- public class ClassB : ClassA
- {
- public virtual void Method1()
- {
- }
- }
Please note that blue color of ClassA changed to black when ClassB inherits ClassA. Also while compiling the solution following error will be generated: 'ClassB': cannot derive from sealed type ‘ClassA' The above shows the working of sealed keyword with class. Class can be sealed for inheritance with the sealed keyword.
Sealed Keyword with Methods Like classes we cannot apply sealed keyword to methods directly. Sealed keyword in methods is used to stop further overriding of the virtual methods during Inheritance.
Let’s see an example to understand the above statement:
- public class ClassA
- {
- public virtual void Method1()
- {
- }
- }
-
- public class ClassB : ClassA
- {
- public override void Method1()
- {
- }
- }
-
- public class ClassC : ClassB
- {
- public override void Method1()
- {
- }
- }
-
- public class ClassD : ClassC
- {
- public override void Method1()
- {
- }
- }
This code works perfectly. We can see each class overrides virtual method Method1 and no compilation error occurs. Now let’s add sealed keyword while overriding Method1 in ClassC.
- public class ClassA
- {
- public virtual void Method1()
- {
- }
- }
-
- public class ClassB : ClassA
- {
- public override void Method1()
- {
- }
- }
-
- public class ClassC : ClassB
- {
- public sealed override void Method1()
- {
- }
- }
-
- public class ClassD : ClassC
- {
- public override void Method1()
- {
- }
- }
Now after compiling the code, the following error generates:
'ConsoleApplication1.ClassD.Method1()': cannot override inherited member 'ConsoleApplication1.ClassC.Method1()' because it is sealed
The above example and explanation shows the working of sealed keyword with method. Method can be sealed for overriding with the sealed keyword.
I hope these simple examples will help you in understanding the working of Sealed keyword with Classes and Methods.
Happy Coding.