Abstract Class in C#

1 - The abstract modifier

We use the abstract modifier to define classes or class members (methods, properties, events, or indexers) to indicate that these members must be implemented in the classes that derive from them.

 

 

2 - Abstract classes and members

When we declare a class as abstract, we are indicating that this class is going to be used as a base class for other classes, since it cannot be instantiated itself.

An abstract class can contain both abstract and non-abstract members, and all abstract members must be implemented in the class that inherits from it.

To continue with the example we saw in interfaces in OOP, we'll use the example of pieces.

public abstract class Pieza
{
    public abstract decimal Area();
    protected abstract decimal Perimetro();
}

As we can see, unlike interfaces, in abstract classes we can include access modifiers.

And as we did with interfaces, in the class that is going to implement the abstract class, we use a colon and the class name.

Unlike interfaces, in classes that inherit from an abstract class we must override each of its methods. To do this, as we saw in the post about polymorphism, we use the override keyword as seen in the example. In interfaces, we simply implement the method, we do not override it.

public class Cuadrado : Pieza
{
    readonly decimal Lado;
    public Cuadrado(decimal lado)
    {
        Lado = lado;
    }
    public override decimal Area()
    {
        return Lado * Lado;
    }

    public override decimal Perimetro()
    {
        return Lado * 4;
    }
}

And as we can see, we can instantiate the object without any problem:

Cuadrado cuadrado = new Cuadrado(3);

 And finally, we see how we can include non-abstract members within the abstract class, which we can define as a default implementation:

public abstract class Pieza
{
    public abstract decimal Area();
    public abstract decimal Perimetro();
    public bool EjemploMetodo()
    {
        return false;
    }

    public int ValorNatural = 1;
}

These methods are not required to be implemented in the classes that inherit from the abstract class, but we can mark them as virtual to allow overriding the method.

As a special note, the compiler will not allow us to include the sealed modifier in abstract classes because, since it cannot be inherited, we would not be able to implement it and it would be meaningless.

 

 

3 - Real world use of an abstract class

As we've explained, abstract classes are used as base classes and that's where all their power lies. They allow us to detect common code and extract it there.

A very clear example would be, for example, if we have events, different types of events, that we need to process.

Car rentals and motorcycle rentals. When we are processing those events we need to make sure, for example

The car is not rented, as well as the motorcycle is not rented either. For that, we need to check in their respective databases that they are not rented. By combining generics (which we will see later) along with abstract classes, we can write very powerful code, but for now we'll look at a simpler example.

As in the previous example, we'll work with geometric figures since it's an easy example to understand.

As we know, we can calculate the area of a triangle using its hypotenuse and one of its sides. And this is true for all different types of triangles. That's why this method is common and should be put inside the abstract class.

public abstract class TrianguloBase
{
    public abstract decimal Perimetro();

    public double CalcularAreaConHipotenusa(int lado, int hipotenusa)
    {
        double ladob = Math.Sqrt(Math.Pow(hipotenusa, 2) - Math.Pow(lado, 2));
        return lado * ladob / 2;
    }
}

And when we define any other triangle, we are not going to define that method in particular.

public class Escaleno : TrianguloBase
{
    public override decimal Perimetro()
    {
        throw new NotImplementedException();
    }
}
public class Acutangulo : TrianguloBase
{
    public override decimal Perimetro()
    {
        throw new NotImplementedException();
    }
}

 

However, we can access it without issue once the variables are initialized

Escaleno escalenno = new Escaleno();
Acutangulo acutangulo = new Acutangulo();

escalenno.CalcularAreaConHipotenusa(1, 5);
acutangulo.CalcularAreaConHipotenusa(1, 7);

 

 

4 - Abstract class vs interface in C#

As you have seen, the use of abstract classes is very similar to interfaces, however, we use one or the other depending on the context, as their usage can overlap.

  1. The main difference we can observe is that in abstract classes we can specify the access modifier, while in interfaces we cannot modify it.
  2. When using interfaces, we can implement multiple interfaces. While we can only use one abstract class as a base.
  3. In an abstract class, since we can include non-abstract members, we can provide a default implementation.  Since C#8 we can create default members.
  4. In an abstract class we can include a constructor, whereas in an interface we cannot.
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é