About
In this code snippet, we’ll take a look at the sealed keyword in C#.
In the following example, we will make a sealed class and a sealed method. Then we’ll try inheriting from the sealed class and overriding the sealed method. As you will be able to see we’ll get an error as sealed methods can’t be overridden and sealed classes can’t be inherited from.
So the whole purpose of the sealed keyword is to “seal” a class or method and thus prevent inheriting/overriding.
Let’s see how to use the sealed keyword in the code example below.
Code:
using System; namespace Sealed { class Program { static void Main(string[] args) { } } class MyClass { public virtual void MyMethod() { Console.WriteLine("Some text."); } } sealed class MySecondClass : MyClass { public sealed override void MyMethod() { Console.WriteLine("Some text."); } } //As you can see we can't inherit from a sealed class. class MyThirdClass : MySecondClass { //As you can see we can't override a sealed method. public override void MyMethod() { Console.WriteLine("Some text."); } } }
Result:
Sealed classes can’t be derived from and sealed methods can’t be overridden.