Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata