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?
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.
- Classes and Constructors
- Static Members, Constants, and Extension Methods
- Anonymous and Nullable Types
- Abstract Classes (Current article)
- Queue, Stack, Hashtable
- Generic List and Dictionary
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:
An abstract class can contain abstract methods. An abstract method doesn’t contain implementation just a definition with the
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
public override void Print()
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:
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:
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#.