77
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:
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.