C# | Virtual Methods

Hassan BOLAJRAF - Jul 23 - - Dev Community
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.

Syntax:

public class BaseClass
{
    public virtual void MyVirtualMethod()
    {
        // Base class implementation
    }
}

public class DerivedClass : BaseClass
{
    public override void MyVirtualMethod()
    {
        // Derived class implementation
    }
}
Enter fullscreen mode Exit fullscreen mode

Example:

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

What Next?

Virtual methods provide a way to implement and leverage the concept of dynamic method dispatch in object-oriented programming.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player