Virtual Methods:
In C#, a virtual function or method is a function that is declared in the base class and can be overridden in the derived class. The virtual keyword is used to modify a method, property, indexer, or event declaration, and allow it to be overridden in a derived class.
Method Overriding:
Method overriding is a feature in C# that enables a derived class to provide a different implementation of a method that is already defined in its base class. This allows you to redefine the behavior of a method in the derived class, tailoring it to the derived class's specific needs.
To override a method in C#, the following conditions must be met:
- Inheritance: The derived class must inherit from the base class.
- Method Signature: The method in the derived class must have the same name and parameter list as the method in the base class.
- The method in the base class must be marked with the virtual keyword.
- The method in the derived class uses the override keyword to override the base class method.
Example:
class Parent
{
public virtual void Print()
{
Console.WriteLine("This is the Print method of the Parent class.");
}
}
class Child : Parent
{
public override void Print()
{
Console.WriteLine("This is the Print method of the Child class.");
}
}
class Program
{
public static void Main()
{
Child childDerived = new Child();
childDerived.Print();
}
}
In this example, when childDerived.Print(); is called, the Print method of the Child class is executed, not the one from the Parent class, because it's overridden in the Child class.