CSharp - sealed class and method

Introduction

You can add sealed keyword to a class to prevent it from inheritance.

Consider the following code.

Here the compiler is preventing the inheritance process.

sealed class ParentClass
{
        public void ShowClassName()
        {
            Console.WriteLine("Inside Parent.ShowClassName");
        }
}
class ChildClass : ParentClass //Error
{
        //Some code
}

We will receive following error: 'ChildClass': cannot derive from sealed type 'ParentClass'.

We can use sealed keyword with methods.

using System;
class ParentClass
{
    public virtual void ShowClassName()
    {
        Console.WriteLine("Inside Parent.ShowClassName");
    }
}
class ChildClass : ParentClass
{
    sealed public override void ShowClassName()
    {
        Console.WriteLine("Inside ChildClass.ShowClassName");
    }
}
class GrandChildClass : ChildClass
{
    public override void ShowClassName()
    {
        Console.WriteLine("Inside GrandChildClass.ShowClassName");
    }
}

Note

A sealed class cannot be a base class.

A sealed class cannot be abstract.

You can use the keyword sealed for methods and classes.

You cannot use sealed keyword to member variables.

You can use readonly or const in those contexts.

We can declare constants like a variable.

We can assign a value to a readonly field during the declaration time or through a constructor.

To declare a constant variable, prefix the keyword const before the declaration.

Constants are implicitly static.

Related Topic