3.17. Polymorphism via Interfaces

Problem

You need to implement polymorphic functionality on a set of existing classes. These classes already inherit from a base class (other than Object), thus preventing the addition of polymorphic functionality through an abstract or concrete base class.

In a second situation, you need to add polymorphic functionality to a structure. Abstract or concrete classes cannot be used to add polymorphic functionality to a structure.

Solution

Implement polymorphism using an interface instead of an abstract or concrete base class. The code shown here defines two different classes that inherit from ArrayList:

public class InventoryItems : ArrayList
{
    // ...
}

public class Personnel : ArrayList
{
    // ...
}

We want to add the ability to print from either of these two objects polymorphically. To do this, an interface called IPrint is added to define a Print method to be implemented in a class:

public interface IPrint
{
    void Print( );
}

Implementing the IPrint interface on the InventoryItems and Personnel classes gives us the following code:

public class InventoryItems : ArrayList, IPrint
{
    public void Print( )
    {
        foreach (object obj in this)
        {
            Console.WriteLine("Inventory Item: " + obj);
        }
    }
}

public class Personnel : ArrayList, IPrint
{
    public void Print( )
    {
        foreach (object obj in this)
        {
            Console.WriteLine("Person: " + obj);
        }
    }
}

The following two methods TestIPrintInterface and CommonPrintMethod show how any object that implements the IPrint interface can be passed ...

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.