O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required