I don't really understand - when am I supposed to use virtual functions?I'll be glad if someone could explain it to me, thanks.
Virtual methods are the key to polymorphism. A method marked as virtual can be overriden in derived classes, to alter or specialize the behavior of the class.
Example:
class Base
{
    public virtual void SayHello()
    {
        Console.WriteLine("Hello from Base");
    }
}
class Derived : Base
{
    public override void SayHello()
    {
        Console.WriteLine("Hello from Derived");
    }
}
static void Main()
{
    Base x = new Base();
    x.SayHello(); // Prints "Hello from Base"
    x = new Derived();
    x.SayHello(); // Prints "Hello from Derived"
}
Note that you can redeclare (not override) a method that is not virtual, but in that case it won't participate in polymorphism:
class Base
{
    public void SayHello() // Not virtual
    {
        Console.WriteLine("Hello from Base");
    }
}
class Derived : Base
{
    public new void SayHello() // Hides method from base class
    {
        Console.WriteLine("Hello from Derived");
    }
}
static void Main()
{
    Base x = new Base();
    x.SayHello(); // Prints "Hello from Base"
    x = new Derived();
    x.SayHello(); // Still prints "Hello from Base" because x is declared as Base
    Derived y = new Derived();
    y.SayHello(); // Prints "Hello from Derived" because y is declared as Derived
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With