How To Use Abstract Classes, Abstract Methods, and Virtual Methods In C#

When you are making something for a project that will have multiple classes utilizing the same type of methods, variables, or whatever, you can use an “Abstract Class” to hold the base variables, methods, etc, and have each individual class inherit from the abstract one.

In this case, the word “Abstract” is similar in meaning to the term “Modular”. And similar to “Modular Design” development methodologies, abstract classes allow you to customize the various instances of inheritance.

An example of this could be an assortment of player characters in an RPG. Whether you choose the Wizard, the Warrior, or the Rogue, each character will still have Health, Experience Points, Currency, etc. All of these variables can be set in the abstract class and modularly established within the individual characters' scripts.

To do this, see the example scripts below.

Within an “Abstract Class”, you can also create “Abstract Methods” as well as “Virtual Methods”.

An “Abstract Method” is similar to the variables that we created in how it works.

The image above depicts the declaration of the “Abstract Method” within the Monobehavior class while the image below shows the implementation from within the inheriting class.

[Important Note!]

Abstract methods do NOT have implementations. The “Override” method is where the implementation would need to be placed.

[Another Important Note!!]

If you use an Abstract Method, then the inheriting class MUST implement this method.

And lastly, there is the “Virtual Method”. Think of these similarly to the “Abstract Methods” except that while the Abstract Methods FORCE implementation, Virtual Methods can contain implementations that can be shared or overridden.

Similar to the previous examples, the image above depicts the declaration of the “Virtual Method” within the Monobehavior class while the image below shows the implementation from within the inheriting class.

You can even add additional functions to the override method that’s still specific to that implementation.

And that’s it! “Abstract Classes”, Abstract Methods”, and “Virtual Methods” should make an amazing addition to your coding repetoir!

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!