What is the purpose of the “virtual” keyword in C#?

In C#, the virtual keyword is used to declare a method, property, or event that can be overridden in a derived class. Its purpose is to achieve polymorphism.

When a method, property, or event in a base class is marked with the virtual keyword, a derived class can override that member by using the override keyword. This allows the derived class to provide its own implementation instead of inheriting from the base class’s implementation.

Members declared using the “virtual” keyword are known as virtual members. It allows the base class reference to call the implementation of the derived class when pointing to a derived class object. This enables runtime polymorphism, where the appropriate method is called based on the actual type of the object during runtime.

In summary, the purpose of the virtual keyword is to allow derived classes to override members of the base class, enabling polymorphism.

bannerAds