Alex Rivera | Logout

Is it possible to implement mixins in C#?

Asked 2008-11-01T05:14:33.537
77

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!

Edit
Report

1 Answer

14

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.

answered 2011-10-13T11:43:43.690

Your Answer