Saturday 5 April 2014

Method Group Conversion

Method Group Conversions (delegates)

C# 2.0 includes a feature called method group conversion that simplifies the syntax used to assign a method to a delegate. Method group conversion allows you to assign the name of a method to a delegate, without the use new or explicitly invoking the delegate's constructor.

The Old Way

public class MethodGroupConversion
{
  public delegate string ChangeString(string str);
  public ChangeString StringOperation;

  public MethodGroupConversion()
  {
    StringOperation = new ChangeString(AddSpaces);
  }

  public string Go(string str)
  {
    return StringOperation(str);
  }

  protected string AddSpaces(string str)
  {
    return str + " ";
  }
}

The New Way

We replace the constructor with a more straightforward assignment:
public MethodGroupConversion()
{
  StringOperation = AddSpaces;
}