Home » .NET » Abstract » C# » Polymorphism » Polymorphism and Abstract in C#

Polymorphism and Abstract in C#

Let’s say you want to define a base class that other classes will inherit from:

We want to make sure that everything that inherits from this class will implement its own version of the CreateBrushes() method. If this method isn’t implemented then we will get a runtime exception every time our inherited class is instantiated. This is one way of ensuring that inherited classes provide an implementation of a method. However, we only find out the problem at runtime. A better solution would be to get an error at compile time. This is where the abstract keyword comes in. Let’s change our method definition of CreateBrushes() to be abstract like this:

You’ll notice that I’ve replace the virtual keyword with the abstract keyword. This has a similar effect, but we no longer need to provide a default body. The compiler will make sure that anything that inherits from this class implements the CreateBrushes() method.

If you try and compile now you will see the following error:

The only way you can use the abstract keyword within a class is if the class itself is also defined as abstract. So you need to add abstract to your class definition. Our updated class definition now becomes:

When a class inherits from this base class it must provide an implementation of the CreateBrushes() method. It’s also important that when defining this method it uses the override keyword. See my post about the difference between polymorphism in C++ and C# to understand why (see Polymorphism in C++ and C#). Here’s an example of an inherited class: