What is a Virtual Function in .NET?
A virtual function is a function that can be overridden in the inheriting class. If you don't inherit, you will be able to access the base function. Any time you overwrite a function, the newer function must have the override keyword to indicate you're overriding the base class.
In the below example, the name written is bloggs joe because it is using the overriding function.
class Program
{
static void Main(string[] args)
{
person Emp = new employee();
Emp.FirstName = "Joe";
Emp.SurName = "bloggs";
Console.WriteLine(Emp.FullName();
Console.ReadKey();
}
}
class person
{
public string FirstName { get; set; }
public string SurName { get; set; }
public virtual string FullName()
{
return FirstName + " " + SurName;
}
}
class employee : person
{
string empNo;
public override string FullName()
{
return SurName + " " + FirstName;
}
}
Tags - .NET
Last Modified : June 2023