Virtual Methods and Properties
Explore how to override virtual methods and properties in C# to customize behavior in derived classes. Understand using the base keyword to extend functionality and the sealed keyword to prevent further overriding, helping you master inheritance and polymorphism in object-oriented C# programming.
We'll cover the following...
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}}
Suppose 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. However, derived classes like Cat or Dog require specific implementations of the Voice() method. For example, cats meow and 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.
Overriding a method
We have three classes: Animal, Cat, and Dog. The latter two classes inherit the Voice() method from Animal but override it with different implementations.
First, let's look at the base class where the method is defined.
Line 1: We declare a file-scoped namespace.
Line 7: We use the
virtualkeyword to allow derived classes to override theVoicemethod.Line 9: We provide a default implementation that prints “Grrrrr”.
Now that we have a base class with a virtual method, we can ...