In C#, the virtual and override keywords are used to implement runtime polymorphism, allowing derived classes to provide specific implementations for methods defined in a base class. Here's an in-depth explanation of these keywords:
Virtual Keyword
The virtual keyword is used in a base class to indicate that a method, property, event, or indexer can be overridden in any derived class. When a method is marked as virtual, it means that the method has a default implementation in the base class, but derived classes can provide their own specific implementation.
Example
public class Animal
{
// Virtual method
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound");
}
}
Override Keyword
The override keyword is used in a derived class to indicate that a method, property, event, or indexer is intended to override a member in the base class. The override keyword ensures that the method in the derived class has the same signature as the method in the base class and provides a new implementation for the base class's virtual method.
Example
public class Dog : Animal
{
// Override method
public override void MakeSound()
{
Console.WriteLine("Dog barks");
}
}
Detailed Example
Let's create a more detailed example to illustrate how virtual and override work together:
Base Class with Virtual Method
Top comments (0)