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 Code for 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
Subscribe to our YouTube Channel: Testing Talks Latest
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x