Mixin Pattern (Class?) in C#

Mixin class is not a pattern because mixin is really not a pattern. It is, rather, a peculiar way in which class inheritance can be accomplished. The famous design patterns book defines mixin class in its opening chapter using these words:

A mixin class is a class that is intended to provide an optional interface or functionality to other classes. It’s similar to an abstract class in that it is not intended to be instantiated. Mixin classes require multiple inheritance.

Gamma et al., Design Patterns: Elements of Reusable Object-Oriented Software

This definition is basically correct, but it requires one additional note before putting it into the C# environment.

Mixin class requires multiple inheritance, plus it is abstract. In terms of C# as a programming language with single inheritance only, this means that mixin will in fact be the interface. Interfaces are abstract, and they can be inherited, that is, implemented even when the class already inherits from another class.

In C# we can create a mixin with a combination of an interface plus extension methods. LINQ is the canonical example of this with two core interfaces IEnumerable<T> and IQueriable<T> and a collection of extension methods on those interfaces.

It’s easy to create your own mixins.

For example, say I want to provide location functionality to various entities. I can define an interface like this:

public interface IPlay {  
  string File
  { 
     get; set; 
  }    
} 

And then some extension methods for that interface:

static class PlayExtensions {    
    public static void PlayAudio(this IPlay play) { 
            ///
    }
   public static void PlayVideo(this IPlay play) { 
        ////
   }
}




Now, if we’ve got some entities like:

public class CameraPlayer: IPlay 
{
public string File { get; set; }
}

public class DVDPlayer : IPlay {
public string File { get; set; }
}

We can use the mixin like this:

var dvdPlayer = new DVDPlayer { File = “..?” } ;
dvdPlayer.Audio();
dvdPlayer.Video();

Take Away is:

  • Extension method acts as any other method defined on the class. However, it can only see public members of the class.