Simulating Multiple Inheritance in C# 3.0
It is possible to simulate multiple inheritance in C#, in a limited way, by applying extension methods to interfaces. An example is shown below. Note that this works only for method implementation inheritance, but not for properties or other kinds of base members. The C# team originally considered including extension properties in C# 4.0, but then dropped the feature. (F# does offer extension "everything", including properties.)
You probably will not use this approach in order to simulate multiple inheritance very often. However, the capacity to add extension methods to interfaces, as such, is a powerful feature.
using System;
// This test shows how to simulate multiple inheritance in C#.
// Requires .Net Framework 3.5 as target framework.
namespace Test {
interfaceIBase1 { }
static class Base1Implementation {
internal static void Base1Method(thisIBase1 base1) {
Console.WriteLine("Base1Method called.");
}
}
interface IBase2 { }
static class Base2Implementation {
internal static void Base2Method(thisIBase2 base2) {
Console.WriteLine("Base2Method called.");
}
}
class Derived: IBase1, IBase2 { }
static class Program {
static void Main() {
var derived = newDerived();
derived.Base1Method(); // Writes "Base1Method called."
derived.Base2Method(); // Writes "Base2Method called."
}
}
}