Posted by: Cirilo Meggiolaro | 01/27/2009

Tip of the day #105 – Virtual members

A virtual member is a method, property, indexer or event that may be overridden in a derived class. In theory, there are basically two types of virtual members: virtual and pure virtual members. There is no pure virtual keyword for C#. You may use abstracts members though. Let’s focus on virtual members for now.

By default, members are not virtual and therefore cannot be overridden. If you want to allow the creation of derived versions for the same members you have on the base type and ensure version compatibility, you may use the virtual keyword on the base class and the override keyword on the derived members.

How to…

The following example shows a base type called Language and some derived types for languages such as English, German and Portuguese. There is a virtual method declared called GetSalutation implemented in the base class. Each derived class has its own implementation of that method.

public class Language
{
    public virtual string GetSalutation()
    {
        return “Hello World!”;
    }
}

public class English : Language
{
    public override string GetSalutation()
    {
        return “Hello World!”;
    }
}

public class German : Language
{
    public override string GetSalutation()
    {
        return “Hallo Welt!”;
    }
}

public class Portuguese : Language
{
    public override string GetSalutation()
    {
        return “Olá Mundo!”;
    }
}


Responses

  1. I´m sad you did not implement the Japanese derived class in the sample…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: