views:

86

answers:

2

I often need to implement an interface by delegating the implementation to a member of my class. This task is quite tedious because, even though Visual Studio generates stubs for the interface methods, I still have to write the code to delegate the implementation. It doesn't require much thinking, so it could probably be automated by a code generation tool...

I'm probably not the first one to think of this, so there must be such a tool already, but I couldn't find anything on Google... Any idea ?


EDIT : it seems that ReSharper can do it, but it's pretty expensive... is there a free alternative with the same feature ?

+1  A: 

You could try this : http://www.codeproject.com/KB/codegen/decorators.aspx?display=PrintAll&fid=1532149&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2837870

Preet Sangha
Thanks for you answer ! This tool looks nice, but it only allows to apply this pattern for types in the same project. I need to do it for BCL types (typically `ICollection<T>` or `IDictionary<K,V>`)
Thomas Levesque
A: 

... see dynamic proxy...

However...

The ability to delegate interface implementation to an instance variable or type [as in typeof(type)], is a greatly needed language feature of C# and VB.Net. With the absence of multiple inheritance and the prevalence of sealed and non-virtual methods and properties, the amount of fluff code required is daunting.

I would think the following language enhancement would work... //C#

interface IY_1
{
  int Y1;
  int Y2;
}
...
..
interface IY_n
{
....
..
}


class Y : IY_1, IY_2, ....,IY_n
{
  private readonly Oy_1 Oy_1 = new Oy_1() supports IY_1, IY_2,...etc;   // <<-----
  private readonly Oy_2 Oy_2 = new Oy_2() supports IY_3, IY_8,...etc;
  public int Y2 {...}
}

The "supports" keyword (or equivalent such as "defaults") would identify an ordered list of class field values that "assist" in the implementation of one or more interfaces, using the normal name and signature mappings semantics of interface of name and signature correspondence. Any local implementation would have precedence and, as well, a single interface may be implemented by multiple field values.

George
I agree that it would be an interesting feature... but I'm not sure MS would consider it useful enough to make it into the language
Thomas Levesque