What is use of virtual keyword in C#

The virtual keyword in C# is used to allow a method, property, or event in a base class to be overridden in a derived class. A virtual member does not have to be overridden, but if it is, the overridden version in the subclass will be executed at runtime, enabling polymorphic behavior.

Example of virtual Keyword in a class:

class Animal
{
public virtual void MakeSound() // virtual method
{
Console.WriteLine(“Some generic animal sound”);
}
}

class Dog : Animal
{
public override void MakeSound() // override in derived class
{
Console.WriteLine(“Bark”);
}
}

Usage:

Animal a = new Dog();
a.MakeSound(); // Output: Bark

Explanation:

  • The MakeSound method in Animal is marked as virtual.
  • The Dog class overrides it using the override keyword.
  • When calling MakeSound on an Animal reference holding a Dog object, the overridden Dog method executes at runtime.
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x