What are Virtual Methods?

mtnclimber10 picture mtnclimber10 · Mar 7, 2009 · Viewed 61.7k times · Source

Why would you declare a method as "virtual".

What is the benefit in using virtual?

Answer

cgreeno picture cgreeno · Mar 7, 2009

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()
}