C# Sealed Keyword

C# Code Snippets Sealed Keyword
Share:

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.
Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger