Home >Backend Development >C++ >C# | Virtual Methods
Note You can check other posts on my personal website: https://hbolajraf.net
In C#, a virtual method is a method that can be overridden in derived classes. This allows for polymorphism, where a base class reference can be used to invoke methods on a derived class object.
public class BaseClass { public virtual void MyVirtualMethod() { // Base class implementation } } public class DerivedClass : BaseClass { public override void MyVirtualMethod() { // Derived class implementation } }
Consider the following example:
using System; public class Animal { public virtual void MakeSound() { Console.WriteLine("Animal makes a generic sound"); } } public class Dog : Animal { public override void MakeSound() { Console.WriteLine("Dog barks"); } } public class Cat : Animal { public override void MakeSound() { Console.WriteLine("Cat meows"); } } class Program { static void Main() { Animal myDog = new Dog(); Animal myCat = new Cat(); myDog.MakeSound(); // Output: Dog barks myCat.MakeSound(); // Output: Cat meows } }
In this example, the Animal class has a virtual method MakeSound(). The Dog and Cat classes override this method with their own implementations. When instances of Dog and Cat are assigned to Animal references, the overridden methods are called based on the actual object type, demonstrating polymorphism.
Virtual methods provide a way to implement and leverage the concept of dynamic method dispatch in object-oriented programming.
The above is the detailed content of C# | Virtual Methods. For more information, please follow other related articles on the PHP Chinese website!