Post

C# | Virtual Methods

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class BaseClass
{
    public virtual void MyVirtualMethod()
    {
        // Base class implementation
    }
}

public class DerivedClass : BaseClass
{
    public override void MyVirtualMethod()
    {
        // Derived class implementation
    }
}

Example:

Consider the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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.

What Next?

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

This post is licensed under CC BY 4.0 by the author.