What is 'virtual' keyword?
This particular keyword or modifier is used for the base class method. The usage of this 'virtual' keyword is to make the base class method overridden which can be later replaced in derived classes.
In C#, the 'virtual' keyword is used to modify a method, property, or indexer declaration in a base class to allow it to be overridden in derived classes. It is used in combination with the override keyword in derived classes to provide a new implementation of the 'virtual' member.
Here are a few key points about the 'virtual' keyword:
-
Virtual Methods: When a method is declared as 'virtual' in a base class, it means that the method can be overridden by derived classes. The base class provides a default implementation of the 'virtual' method, but it can be overridden and replaced with a different implementation in derived classes.
-
Method Overriding: To override a 'virtual' method in a derived class, you need to use the override keyword. The overriding method in the derived class must have the same signature as the 'virtual' method in the base class.
-
Runtime Polymorphism: Virtual methods enable runtime polymorphism, allowing you to treat derived objects as instances of the base class and invoke the appropriate implementation based on the actual type of the object at runtime.
-
Optional Implementation: The 'virtual' keyword is optional, and you can omit it if you don't intend to override the method in derived classes. Non-virtual methods are implicitly sealed and cannot be overridden.
Here's an example that demonstrates the usage of the 'virtual' keyword:
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape.");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}
class Rectangle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a rectangle.");
}
}
class Program
{
static void Main(string[] args)
{
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();
shape1.Draw(); // Output: Drawing a circle.
shape2.Draw(); // Output: Drawing a rectangle.
}
}
In this example, the 'Shape' class has a 'virtual' method 'Draw()'. The 'Circle' and 'Rectangle' classes inherit from 'Shape' and override the 'Draw()' method with their own implementations.
In the Main method, we create instances of 'Circle' and 'Rectangle' but store them in variables of type 'Shape'. When we call the 'Draw()' method on these objects, the appropriate implementation based on the actual type of the object is invoked. This demonstrates runtime polymorphism achieved through the use of 'virtual' methods.