3.4. Polymorphism via Concrete or Abstract Base Classes

Problem

You need to build several classes that share many common traits. These classes may share common properties, methods, events, delegates, and even indexers; however, the implementation of these may be different for each class. These classes should not only share common code but also be polymorphic in nature. That is to say, code that uses an object of the base class should be able to use an object of any of these classes in the same manner.

Solution

Use an abstract base class to create polymorphic code. To demonstrate the creation and use of an abstract base class, here is an example of three classes, each defining a media type: magnetic, optical, and punch card. An abstract base class, Media, is created to define what each derived class will contain:

public abstract class Media
{
    public abstract void Init( );
    public abstract void WriteTo(string data);
    public abstract string ReadFrom( );
    public abstract void Close( );

    private IntPtr mediaHandle = IntPtr.Zero;

    public IntPtr Handle
    {
        get {return(mediaHandle);}
    }
}

Next, the three specialized media type classes, which inherit from Media, are defined to override each of the abstract members:

public class Magnetic : Media { public override void Init( ) { Console.WriteLine("Magnetic Init"); } public override void WriteTo(string data) { Console.WriteLine("Magnetic Write"); } public override string ReadFrom( ) { Console.WriteLine("Magnetic Read"); string data = ""; return (data); ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.