Posted by: Cirilo Meggiolaro | 01/28/2009

Tip of the day #106 – Abstract members

Some thoughts first

  • Abstract members are methods, properties, indexers and events that must be overridden on derived classes;
  • To the compiler an abstract member indicates that its implementation is incomplete;
  • An abstract member can only be declared within an abstract class;
  • An abstract member must be overridden in a derived class. Otherwise, a compiler error will be raised;
  • Only abstract classes that inherit from another abstract class are exempt to override the abstract members;
  • Abstract members cannot have code implementation. Only signatures are allowed;
  • Use it to enforce that derived classes override those members.

How to..

The following example creates an abstract class called Language with an abstract method called GetSalutation. You will notice that only the method signature is available. There is no method body for the GetSalutation operation.

public abstract class Language
{
    /// Defines an abstract method.
    public abstract string GetSalutation();
}

public class English : Language
{
    /// Override is mandatory for abstract methods.
    public override string GetSalutation()
    {
        return “How are you?”;
    }
}

public class Japanese : Language
{
    /// Override is mandatory for abstract methods.
    public override string GetSalutation()
    {
        return “Ogenki desu ka?”;
    }
}

public class French : Language
{
    /// Override is mandatory for abstract methods.
    public override string GetSalutation()
    {
        return “Comment allez-vous”;
    }
}

Advertisements

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: