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 ?
I've been using Resharper for a few months now, and it has a great feature to do this.
For instance, write the following code:
class MyList<T> : IList<T>
{
private readonly IList<T> _list;
}
Place the caret on _list
, press Alt + Ins (shortcut for Generate Code), and select "Delegating members". Select the members you need, and R# generates delegating members for them:
public void Add(T item)
{
_list.Add(item);
}
public void Clear()
{
_list.Clear();
}
public bool Contains(T item)
{
return _list.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
return _list.Remove(item);
}
public int Count
{
get { return _list.Count; }
}
public bool IsReadOnly
{
get { return _list.IsReadOnly; }
}
public int IndexOf(T item)
{
return _list.IndexOf(item);
}
public void Insert(int index, T item)
{
_list.Insert(index, item);
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
public T this[int index]
{
get { return _list[index]; }
set { _list[index] = value; }
}