C# Virtual Classes & Methods

Virtual classes are a useful way to define “default” code using inheritance, while still allowing for class-specific differences. Like Abstract classes, but less forced.

Vincent Taylor
2 min readSep 6, 2021

Virtual classes, like Abstract classes, can act as base classes and allow multiple other classes to inherit from them, gaining their (public & protected) variables and methods as if the derived classes had them in themselves.

The base Vehicle class which is Virtual to allow overriding
An inheriting Car class, which overrides the Forward method but leaves everything else as default

While the above “Car” class is much simpler than the “Vehicle” class in terms of code amount, both can do exactly the same things.

Car can call “Forward”, “Backward”, “TurnLeft” and “TurnRight” and everything apart from “Forward” will run just as specified in the “Vehicle” class. The “Forward” method has been overridden by “Car”, so it will run the code inside “Car” instead, when called.

As seen above, the “override” keyword is used in an inheriting class to specify that a Virtual method from the base class should be overridden and not use its default implementation.

The “override” keyword goes after the access modifier, and before the return type, and can be used on any method that inherits from a base class’s Virtual method.

If you don’t want to fully override a method and just wish to add to its implementation, you can do this:

By calling “base.YourMethodName()”, you can run both the default code from the base class, plus any additional code in the above function (before or after the base call).

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Vincent Taylor
Vincent Taylor

Written by Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.

No responses yet

Write a response