Sealed Classes in C#

Sealed Classes are the classes that cannot be inherited. It restrict Inheritance, you cannot use it as a base class. It is define with the help of ‘sealed’ keyword.

Syntax:
sealed class A
{
//class members here
}

When you try to derive a class from sealed class compile time error occurs. ‘Cannot derive from a sealed type’

sealed class A
{
//class members here
}


class B : A // error
{
//code goes here
}

We can use sealed modifier for property or method. But Note that it can only be used with override keyword. Means if there is a virtual method A in base class. And in the derived class you are overriding this method A, so here in the derived class you can use sealed.
class Person
{
protected virtual void Work() { }
}


class Employee : Person
{
sealed protected override void Work() { } // This method is sealed here
}


class Member : Employee
{
// here you cannot access the Work()
}

This way you are restricting the virtual method for its further inheritance.




Note :

– You cannot use abstract modifier with sealed class , because both of them are opposite. Abstract class must be inherited further for providing defination or implementation to the abstract methods whereas sealed class restrict inheritance.

– You can create object of sealed class but cannot inherit it.

– structs cannot be inherited because they are implicitly sealed.