What is a sealed class in C#?
Classes can be defined as data types that are user-defined, representing the state (properties) and the behavior (actions) of an object.
Types of classes
Classes have four major types in C#, which are as follows.
- Abstract class
- Partial class
- Sealed class
- Static class
In this Answer, we’ll only discuss the sealed class.
Sealed class
A type of class that cannot be inherited into any other class and has restricted access to its properties is called a Sealed class.
The main purpose of the sealed class is to restrict the inheritance feature from the class user, i.e., the sealed class cannot be used to generate a derived class. Sealed class can be generated using the sealed keyword.
Example
namespace SealedClass {sealed class Car {}// trying to inherit sealed class// Error Codeclass BMW : Car{}class Program {static void Main (string [] args) {// create an object of BMW classBMW mycar = new BMW();}}}
Explanation
In the above code, the "SealedClass.BMW": cannot derive from sealed type "SealedClass.Car" is generated, showcasing that we cannot generate a derived class from a sealed class.
- Line 2: We declare a class of sealed type using a
sealedkeyword. - Line 8: We try to write a derived class
BMW : Car, and this line generates an error. - Line 12–20: This contains the
mainprogram that creates an object of derived classBMW.
Free Resources