Heard of mix-ins? They’re an alternative to multiple inheritance, made popular recently by Ruby.

Basically, you can use them to “mix in” methods from an interface with their implementations into a class.

In Ruby you can do this by including a module in a class. In C#, you do it by implementing an interface and defining an extension method for the interface.

Here’s a simple example.

First, define the interface. In this case, it won’t have any special features, so the interface is empty. We’ll call it IDebug, as it is going to let us call a method to get details of the object it is implemented on.

public interface IDebug
{
}

After the interface is set, define a static class with an extension method for the interface. We’ll just define one method here, called “GetTypeInfo”.

public static class DebugExtensions
{
  public static string GetTypeInfo(this IDebug debug)
  {
    return String.Format(“{0} ({1}): {2}”
	, debug.GetType().Name
        , debug.GetHashCode().ToString()
        , debug.ToString());
  }
}

The method returns the name of the class (not the interface) where the interface is implemented, plus a few extra bits of information.

Now implement a couple of classes which implement the interface.

class MyClass : IDebug
{
  public override string ToString()
  {
    return “I am an instance of MyClass”;
  }
}

class MyOtherClass : IDebug
{
  public override string ToString()
  {
    return “I am an instance of MyOtherClass”;
  }
}

Now, magically, the method “GetTypeInfo” is included with the class as an extension method.

In the method you call this from, you then need add a “using” declaration for the namespace of the extension class.

After you’ve done that you can call the method from the mix-in.

var myObj = new MyClass();
var myObj2 = new MyOtherClass();
Console.WriteLine(myObj.GetTypeInfo());
Console.WriteLine(myObj2.GetTypeInfo());

The output of this is:

MyClass (7995840): I am an instance of MyClass
MyOtherClass (56251872): I am an instance of MyOtherClass