sealed class in C# with Example
When you have class as base class and you want that any other derived class can not inherit this base class then we declared the base class as sealed class. The sealed keyword also can be used with method, property or event in the derived class to prevent further overriding. This is often done to protect the integrity of a class or to prevent unintentional modifications to its behavior.
Here’s how you can use the sealed keyword in C#:
Sealing a Class:
You can declare a class as sealed class, When you make a class sealed it can not be further overriding, you can not further use it as a base class for other classes.
Example
public sealed class Fruit
{
// Class members
}
Sealing a Method:
You can declare a method sealed. When you make a method sealed it mean it can not further overridden in any derived class. This is typically used to protect the behavior of a method defined in the base class.
Example
// Base class (parent class)
public class Fruit
{
public vistual void Taste()
{
// Method implementation
}
}
// Derive class (child class)
public class Mango: Fruit
{
public sealed override void Taste()
{…