Hello readers, In this session we are going to see Sealed Class in C# with an example. A sealed class is a special class which prevents a class from being inherited by other class. You can declare a class as a sealed class when there is no need to extend it to provide additional functionality.

What is Sealed Class?

A sealed class is class which is declared using the sealed modifier. A Sealed class prevent a class from being inherited by other class. An error occurs if you try to inherit a class that is declared as a sealed class. You can declare a class as a sealed class when there is no need to extend it to provide additional functionality. Since the struct is implicitly sealed by default so if we want to prevent a class for accidental inheritance sealed modifiers should use. We can not declare an abstract class as sealed because for an abstract class it is necessary that it is inherited by other classes to extend its functionality that provides the implementation for abstract property and abstract methods. A sealed modifier can be applied to both a class or a method as well.

The syntax for declaring a Sealed class:

access-modifier sealed class class-name

Why we need a sealed class:

A sealed class is used for security reason for preventing a class from unintended derivation by which the derived class may corrupt the implementation provided in the sealed class. A sealed class is useful when you have public members in it.

In real time software projects, we use sealed class and sealed method to stop a developer to extend a class or override a method accidentally.

Example of Sealed Class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public sealed class BaseClass

{
public void Display()
{
Console.WriteLine("This is a sealed class which can;t be further inherited");
}

}

public class Derived : BaseClass
{

}

class Program
{
BaseClass obj = new BaseClass();
obj.Display();
Console.ReadLine();
}

I

Sinche Base class is declared as sealed class so it will not allow inheritance.

Sealed Class

Key Points about Sealed Class:

  • A class restricts inheritance for security reason.
  • A sealed class is the last class in the class hierarchy..
  • We can declare a Sealed class as a derived class but not as a base class.
  • An abstract class cannot be declared as a sealed class because an abstract class needs to implement functionality an here we are restricting inheritance using the sealed modifier.

View More:

Conclusion:

I hope you would love this post. I would like to have your feedback, comments, and suggestions.

Thank You

Leave a Comment