I do understand that there’s no multiple inheritence in C#. However, I’ve run into a situation in which I really wish it existed. I am creating a custom class that requires me to inherit from CLR types and override a few methods. Unfortunately, I am creating several of these which are very similar. In the interest of DRY, I’d really want to move common functionality to a base class, but then I’d need to inherit from 2 classes. I can use interfaces (and infact I am using one right now) but this solves only half the problem as the method implementations still need to be repeated across several custom classes.
What’s the purist way of achieving what I am trying to do?
EDIT:
Here’s a generic code sample
public class CustomTypeOne : CLRType
{
public override void Execute(HttpContext context)
{
//Some code that's similar across CustomTypeOne, CustomTypeTwo etc
}
public void DoStuff()
{
//Same for all CustomTypes and can be part of a base class
}
//More methods
}
public class CustomTypeTwo : CLRType
{
public override void Execute(HttpContext context)
{
//Some code that's similar across CustomTypeOne, CustomTypeTwo etc
}
public void DoStuff()
{
//Same for all CustomTypes and can be part of a base class
}
//More methods
}
There are a few ways to implement what you are talking about.
Assuming that you have a structure like like
Then it makes sense to want to have a base class, but you can’t. One method that other answers mentioned is composition. However in your case it might be possible to create another static class
Then you have all of your disparate objects that need duplicate functionality call the helper method. The only advantage multiple inheritance would have in this case is that you wouldn’t have to write “DoComplicatedStuff()” over and over, but copy/paste will clean up that problem pretty quick anyway.
EDIT
If you are inheriting from the same type, then you don’t need MI for this