C# – Quick Reference for Abstract Classes

Abstract Classes in C# are classes, intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class. Reference

With other words – what does this mean? An abstract class with abstract methods is built only, with the idea of the methods being overriden by the classes tha inherit from it. Let’s imagine an abstract class Car with 2 abstract methods – StartEngine() and Stop Engine():

A class SmallCar inherits from Car. Thus, we try to write class SmallCar : Car, but the SmallCar is colored with red line below. Anyhow, pressing Ctrl + Dot automatically builds the missing implementation of the abstract classes:

Which is somehow beautiful. And saves a lot of time. 🙂 Furthermore, imagine that we have built another class, BitTruck, which also inherits from Car:

Then, if one wants to start both the BigTruck and the SmallCar, which are added to a list of Cars, this is a possible working code:

And this is how the console looks like:

Pretty nice, eh? Using the inherited classes in a list of the type that they are inheriting. Going further. Imagine that you are in need to use the abstract class with a method, which is the same for all the classes that inherit from it. What do you do? Pretty much, the following is quite enough:

The string method “YearsNeededToDrive” would return the same result from any class, which inherits from car. Without implementation, of course, because the method is not an abstract one:

And this is what is produced:

It is not inherited by the classes, that inherit the base class, because constructors are not to be inherited. Thus, an implementation is needed in both classes:

This is how it is called, now with the parameter yearOfProduction:

And this is the result:

The code from the article is in GitHub here.

Tagged with: , ,