Sealed Modifier in C#

Welcome to this new post, where we’ll talk about two key pieces in object-oriented programming. Even though they’re not used too often, it’s always good to keep them in mind.

Additionally, they are closely related, since using sealed on a class prevents us from inheriting it, and final prevents us from overriding methods.

 

1 - What is the sealed modifier

A sealed class is one that cannot be inherited from. This means you cannot implement it in other classes to access its members.

The easiest way to see it is with an example.

If we recall the example we saw in the inheritance post with vehicles, we had the following:

class Vehiculo
{
    //Código
}

class Coche : Vehiculo 
{
//Código
}

class Moto : Vehiculo
{
//Código
}

Within Coche, we could include van, minivan, sedan, etc.

class Furgoneta : Coche {}
class Furgon : Coche {}
class Turismo : Coche {}

But depending on your business logic, you may want to prevent this functionality. To do so, we can add the sealed modifier, which stops further inheritance.

sealed class Coche : Vehiculo
{
    //Código
}

sealed class Moto : Vehiculo
{
    //Código
}

class Furgoneta : Coche { } //Error
class Furgon : Coche { } //Error
class Turismo : Coche { } //Error

As we can see, we’ve added the modifier to the Coche class, so that no other class can inherit from it.

As shown in the example, implementing the Furgoneta, Furgon and Turismo classes gives us an error stating that you cannot derive from a sealed class.

 

 

2 - Sealed modifier in methods

As we recalled from the post about polymorphism in OOP, you can override methods in derived classes by using the virtual and override modifiers.

class Vehiculo
{
    public decimal VelocidadMaxima { get; set; }
    public int NumeroRuedas { get; set; }
    public string Marca { get; set; }
    public string Modelo { get; set; }

    public Vehiculo(string marca, string modelo)
    {
        Marca = marca;
        Modelo = modelo;
    }
    public virtual void Acelerar()
    {
        Console.WriteLine("Acelerar vehículo");
        //Pisar el acelerador
    }

}

class Moto : Vehiculo
{
    public int Cilindrada { get; set; }

    public Moto(string marca, string modelo, int cilindrada) : base(marca, modelo)
    {
        Cilindrada = cilindrada;
    }

    public override void Acelerar()
    {
        //Girar el puño
        Console.WriteLine("Acelerar Moto");
    }
}

Additionally, you can do the same as we’ve just seen with classes, but with individual methods.

When you use sealed on a method, it means you can no longer override that method in derived classes. So when you call the method, it will always be the one marked as final.

class Moto : Vehiculo
{
    public int Cilindrada { get; set; }

    public Moto(string marca, string modelo, int cilindrada) : base(marca, modelo)
    {
        Cilindrada = cilindrada;
    }

    public sealed override  void Acelerar()
    {
        //Girar el puño
        Console.WriteLine("Acelerar Moto");
    }
}
class Triciclo : Moto
{
    public Triciclo(string marca, string modelo, int cilindrada) : base(marca, modelo, cilindrada)
    {
    }

    public override void Acelerar() //Error
    {
        //Código
    }
}

As we can see in the example, we’ve added the sealed modifier before override, which indicates that from there, that method can’t be inherited anymore. For this reason, if you try to create a method called Acelerar() in a class that inherits from Moto, it’ll give an error because the parent class’s method is sealed.

 

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café