DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

Emulating Multiple Inheritance with Extension Methods

Anders Abel user avatar by
Anders Abel
·
May. 27, 12 · Interview
Like (0)
Save
Tweet
Share
5.16K Views

Join the DZone community and get the full member experience.

Join For Free
Last week I showed some ways to utilize extension methods. In this post I’ll go on with a more advanced example and also discuss some of the limitations.

Method-Only Multiple Inheritance

A combination of interfaces and extension methods can be used to partly work around the single inheritance limitation of C#. Assume that I have a class hierarchy of animals. Some of the animals are possible to ride, but they are spread across the hierarchy and cannot share a common base class. In C# we can use an interface to get a type safe way to indicate that an animal is possible to ride.

public interface IRideable { void Mount(); void Start(); }
public abstract class Animal { public string Name { get; set; } }
public abstract class HorseAnimal : Animal { }
public class Zebra : HorseAnimal { }
public class Horse : HorseAnimal, IRideable
{
    virtual void Mount()
    {
        Debug.WriteLine("Swing into the saddle");
    }
    virtual void Start()
    {
        Debug.WriteLine("Press heels into horse's side");
    }
}
public class Elephant : Animal, IRideable
{
    void Mount()
    {
        Debug.WriteLine("Climb the ladder");
    }
    void Start()
    {
        Debug.WriteLine("Poke behind ears with toes");
    }
} 

If this would have been C++ where multiple inheritance is allowed it would be possible to add a method Ride() to the IRideable interface that combines the mount and start operations needed to take a ride. One way is to add the Ride() method to the Animal with a default implementation that throws an exception, but I don’t like that. I prefer to catch the errors at compile time and not runtime.

A better way in C# is to create an extension method.

public static class RideableExtensions
{
    public static void Ride(this IRideable animal)
    {
        animal.Mount();
        animal.Start();
    }
}

T

hat will allow us to call a Ride() method on any animal implementing IRideable.

Limitations

As good as extension methods are, they are still subject to some limitations. Both of them are related to the fact that they are just a syntactic construct which is expanded during compilation.

No polymorphism

Extension methods have no support for polymorphism. To show the problem, I’ll extend the animal hierarchy with a wild horse and a corresponding Ride method in an extension class.

public class WildHorse : Horse
{
    public void Catch()
    {
        Debug.WriteLine("Catch the horse with lasso");
    }
    public override void Mount()
    {
        Debug.WriteLine("Swing onto back");
    }
    public override void Start()
    {
        Debug.WriteLine("ERROR: Horse already running");
    }
}
 
public static class WildHorseExtensions 
{
    public static void Ride(this WildHorse horse)
    {
        horse.Catch();
        horse.Mount();
        // No need to start, the wild horse is already
        // running for it's life when someoune mounts.
    }
}

I’ve created some sample code to test the new WildHorse class.

Debug.WriteLine("Riding horse...");
Horse horse = new Horse();
horse.Ride();
 
Debug.WriteLine("Riding wild horse...");
WildHorse wildHorse = new WildHorse();
wildHorse.Ride();
 
Debug.WriteLine("Treating wild horse as horse...");
horse = wildHorse;
horse.Ride();

The output shows the problem.

Riding horse...
Swing into the saddle
Press heels into horse's side
 
Riding wild horse...
Catch the horse with lasso
Swing onto back
 
Treating wild horse as horse...
Swing onto back
ERROR: Horse already running

It is clear that the compile time type is used when choosing what extension method to use. If the wild horse is assigned to a Horse reference, the special overload for the wild horse won’t be called. Instead the ordinary IRideable extension is called.

No dynamic support

dynamic horse = new Horse();
 
// Throws a RuntimeBinderException
horse.Ride(); 

Another problem on the same theme is the lack of dynamic support for extension methods. Changing the type of the variable from the last example to dynamic compiles, but gives a runtime error.

The reason is that for non dynamic types, the horse.Ride() syntax is expanded during compilation to RideableExtensions.Ride(horse). To find the correct Ride() method, the compiler searches all static classes in all namespaces included by using blocks. That information is only available in the source file so the runtime binder has no way to know where to search. Eric Lippert explains that the C# team considered adding support for this, but decided it wasn’t worth it.

Inheritance (object-oriented programming)

Published at DZone with permission of Anders Abel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Create a CLI Chatbot With the ChatGPT API and Node.js
  • Journey to Event Driven, Part 1: Why Event-First Programming Changes Everything
  • Strategies for Kubernetes Cluster Administrators: Understanding Pod Scheduling
  • 5 Steps for Getting Started in Deep Learning

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: