DEV Community

Nick
Nick

Posted on

Learn about Sealed Classes in C#

Sealed Classes in C#

In object-oriented programming, the concept of inheritance allows classes to inherit properties and behaviors from other classes. However, there are times when we want to restrict inheritance to prevent further modifications or extension. This is where sealed classes come into play in C#.

A sealed class is a class that cannot be inherited or used as a base class for other classes. It offers a level of protection by sealing off the class itself, preventing any further modification or extension. This feature is particularly useful when we want to ensure that the class's behavior and implementation remain intact and prevent unintended modifications that could break its functionality.

To create a sealed class in C#, we simply use the sealed keyword before the class definition. Here's an example:

sealed class Vehicle
{
    public void Start()
    {
        Console.WriteLine("The vehicle has started.");
    }

    public void Stop()
    {
        Console.WriteLine("The vehicle has stopped.");
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the Vehicle class is defined as sealed. This means that no other class can inherit from it. It has two methods: Start() and Stop(), which are available to use. However, if we were to try to inherit from the Vehicle class, it would result in a compile-time error.

class Car : Vehicle // Error: Cannot derive from sealed type 'Vehicle'
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

One interesting thing to note is that a sealed class can still inherit from other classes. However, it cannot be inherited by other classes. This means that while the sealed class cannot be further extended, it is still capable of inheriting properties and behaviors from its base class.

Additionally, it's worth mentioning that the sealed keyword can also be used to prevent further overriding of methods in derived classes. By marking a method as sealed, we ensure that it cannot be overridden again. This is useful when we want to restrict the modification of existing functionality defined in a base class.

Sealed classes provide a mechanism to restrict inheritance and modification, ensuring that certain classes remain intact and unmodified. They offer an added layer of protection and control over the behavior and implementation of classes, making them a valuable feature in C# programming.

Overall, understanding and using sealed classes can be an important aspect of designing and developing robust and secure applications in C#. It allows developers to carefully control access and modification to certain classes, thereby ensuring the stability and integrity of their applications.

Top comments (0)