What is a virtual method in C#? Also, give a suitable example.
What is a virtual method in C#? Also, give a suitable example.
440
14-Apr-2023
Aryan Kumar
15-Jun-2023A virtual method in C# is a method that can be overridden in a derived class. When a method is declared as virtual in a base class, it allows a derived class to provide its own implementation of the method.
Here is an example of a virtual method in C#:
C#
In the above example, the
Speak()method is declared as virtual in theAnimalclass. This means that any derived class ofAnimalcan override theSpeak()method and provide its own implementation.In the
DogandCatclasses, theSpeak()method is overridden to provide a specific sound for each animal.When an instance of
DogorCatis created and theSpeak()method is called, the implementation of theSpeak()method in the appropriate class will be called.Virtual methods are a powerful feature of C# that allow for polymorphism. Polymorphism is the ability to treat objects of different types in the same way. In the above example, the
Speak()method can be called on an object of any type that inherits fromAnimal. The appropriate implementation of theSpeak()method will be called, depending on the type of object that is used.Virtual methods are often used in conjunction with interfaces. An interface is a collection of abstract methods. An abstract method is a method that does not have an implementation.
When a class implements an interface, it must provide an implementation for all of the abstract methods in the interface. This can be done by providing a concrete implementation of the method, or by overriding a virtual method in a base class.
Virtual methods and interfaces are powerful features of C# that allow for code reuse and flexibility. They can be used to create reusable code that can be used in a variety of situations.