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

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