Is it possible to implement mixins in C#?

I've heard that it's possible with extension methods, but I can't quite figure it out myself. I'd like to see a specific example if possible.

Thanks!


Solution 1:

It really depends on what you mean by "mixin" - everyone seems to have a slightly different idea. The kind of mixin I'd like to see (but which isn't available in C#) is making implementation-through-composition simple:

public class Mixin : ISomeInterface
{
    private SomeImplementation impl implements ISomeInterface;

    public void OneMethod()
    {
        // Specialise just this method
    }
}

The compiler would implement ISomeInterface just by proxying every member to "impl" unless there was another implementation in the class directly.

None of this is possible at the moment though :)

Solution 2:

I usually employ this pattern:

public interface IColor
{
    byte Red   {get;}
    byte Green {get;}
    byte Blue  {get;}
}

public static class ColorExtensions
{
    public static byte Luminance(this IColor c)
    {
        return (byte)(c.Red*0.3 + c.Green*0.59+ c.Blue*0.11);
    }
}

I have the two definitions in the same source file/namespace. That way the extensions are always available when the interface is used (with 'using').

This gives you a limited mixin as described in CMS' first link.

Limitations:

  • no data fields
  • no properties (you'll have to call myColor.Luminance() with parentheses, extension properties anyone?)

It's still sufficient for many situations.

It would be nice if they (MS) could add some compiler magic to auto-generate the extension class:

public interface IColor
{
    byte Red   {get;}
    byte Green {get;}
    byte Blue  {get;}

    // compiler generates anonymous extension class
    public static byte Luminance(this IColor c)     
    {
        return (byte)(c.Red*0.3 + c.Green*0.59+ c.Blue*0.11);
    }
}

Although Jon's proposed compiler trick would be even nicer.