What are Virtual Methods?
Solution 1:
The Virtual Modifier is used to mark that a method\property(ect) can be modified in a derived class by using the override modifier.
Example:
class A
{
public virtual void Foo()
//DoStuff For A
}
class B : A
{
public override void Foo()
//DoStuff For B
//now call the base to do the stuff for A and B
//if required
base.Foo()
}
Solution 2:
Virtual allows an inheriting class to replace a method that the base class then uses.
public class Thingy
{
public virtual void StepA()
{
Console.Out.WriteLine("Zing");
}
public void Action()
{
StepA();
Console.Out.WriteLine("A Thingy in Action.");
}
}
public class Widget : Thingy
{
public override void StepA()
{
Console.Out.WriteLine("Wiggy");
}
}
class Program
{
static void Main(string[] args)
{
Thingy thingy = new Thingy();
Widget widget = new Widget();
thingy.Action();
widget.Action();
Console.Out.WriteLine("Press any key to quit.");
Console.ReadKey();
}
}
When you run the Program your output will be:
Zing
A Thingy in Action.
Wiggy
A Thingy in Action.
Notice how even though Widget called the Action() method defined at the Thingy level, internally Thingy called Widget's StepA() method.
The basic answer is it gives inheritors of a class more flexibility. Of course, you've got to engineer your class well or it could weak havoc.