Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual functions

Tags:

c#

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.

like image 379
Rich Porter Avatar asked Jun 29 '11 12:06

Rich Porter


1 Answers

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
}
like image 152
Thomas Levesque Avatar answered Oct 24 '22 15:10

Thomas Levesque