Virtual Methods and Properties

Learn to override methods and properties.

Override methods

When we inherit a method from a base class, we might need to change its behavior in a child class. Consider the following example:

public class Animal
	public void Voice()
		// Method implementation

Let’s imagine that the Voice() method produces the voice of an animal. For something as generic as the Animal class, we could have a generic implementation of this method. But, for other classes that inherit from Animal, such as Cat or Dog, we must have a different implementation of the Voice() method. Cats meow while dogs bark.

Providing a different implementation for an inherited method is called overriding. In C#, we can only override a method if it was marked as virtual in a base class:

Get hands-on with 1200+ tech skills courses.