#554 – Rules for Matching an Anonymous Method to a Delegate Type

When you declare an anonymous method and assign it to a delegate type or pass it as a delegate-typed parameter, the anonymous method is converted to an instance of the appropriate delegate.  There are several rules that you must follow so that this conversion can happen properly.

  • You can only omit the formal parameter list in the anonymous method declaration if
    • The delegate type’s parameter list has no ref or out parameters
    • The body of the anonymous method does not need to read or write any of the parameters
  • If you include the formal parameter list in the anonymous method declaration, you must include all of the parameters and the type must match for each parameter
  • Any object returned as the return value of the anonymous method must be able to be implicitly converted to the return type of the delegate