Home >Backend Development >C++ >C# | Virtual Methods

C# | Virtual Methods

WBOY
WBOYOriginal
2024-07-24 01:31:141170browse

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.

Syntax:

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:

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.

The above is the detailed content of C# | Virtual Methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn