Different classes may implement the same interface, and that is the common case in software development. What is common as well is that the method from that interface can have the same implementation in those classes. That could be a signal that we are doing something wrong. We don’t want to repeat the code in our classes, but to reuse the common implementation.

To fix this, we can extract this common implementation to a base class, and make our classes implement a base class and then make the base class implement an interface. This will solve our problem, but it is not a complete solution.

Why is that?

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

The problem is that now we can create an instance of our base class, which holds nothing except the common implementation of a method (or methods). This doesn’t make any sense. A class that contains only the common implementation should have a sole purpose to be inherited from.

That’s why we are going to talk about abstract classes in this article.

If you want to see complete navigation of this tutorial, you can do that here C# Intermediate Tutorial.

To download the source code, you can visit Abstract Classes in C# Source Code. 

We are going to split this article into the following sections:

Creating Abstract Classes

To create an abstract class, we use the abstract keyword. The only purpose of the abstract class is to be inherited from and it cannot be instantiated:

Abstract instance error - Abstract Classes in C#

An abstract class can contain abstract methods. An abstract method doesn’t contain implementation just a definition with the abstract keyword:

public abstract void Print(string text);

To implement an abstract method in the class that derives from an abstract class, we need to use the override keyword:

public override void Print()
{
    //method implementation
}

As we could see from a previous picture, an abstract class doesn’t have to have any abstract member but the more important thing is if a class have at least one abstract member, that class must be an abstract class. Otherwise, the compiler will report an error:

Abstract method error - Abstract Classes in C#

Sealed Classes

If we want to prevent our class to be inherited from, we need to use the sealed keyword. If anyone tries to use a sealed class as a base class, the compiler will throw an error:

Sealed classes error - Abstract Classes in C#

Conclusion

In this article, we have learned:

  • How to create an abstract class
  • How to use abstract members and how to implement them
  • What a sealed class is and its purpose

In the next article, we are going to talk about Generics in C#.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!