Stop creating custom delegate types

Note to OSS and framework developers:

Please stop creating custom delegate types.  Use the Action and Func delegates instead.

The problem is that delegate types with the same signature are not convertible to each other.  For example, none of these assignments will work:

public delegate bool CustomMatchingFunction(string value);

public void Custom_delegates_are_bad()
    Predicate<string> match1 = value => value == "Blarg";
    Func<string, bool> match2 = value => value == "Blarg";
    CustomMatchingFunction match3 = value => value == "Blarg";

    match1 = match2;
    match1 = (Predicate<string>)match2;
    match1 = match3;

Although all of the delegate types shown have the same signature, this does not mean that they’re the same type.  They’re neither implicitly nor explicitly convertible from each other.  One of the preliminary LINQ framework design guidelines states:

**Do** use the new LINQ types “Func<>” and “Expression<>” instead of custom delegates and predicates, when defining new APIs.

There are Action delegates for void methods and Func delegates for methods that return values.  If something needs a delegate, use either the generic or specific versions of these delegate types.  Instead of “Predicate”, use “Func<T, bool>”.  Instead of creating a custom void delegate, use “Action”.

By creating custom delegate types, you’re forcing people using your API to either force your custom type into their code, or force them to use a bunch of “wrapper methods” that wrap, convert and call your custom delegate type.

If you declare even a single delegate type in your code (and you’re using .NET 3.5), stop and make sure there isn’t already an Action or Func delegate that works for you.

Looking for Extreme Programmers in Austin, TX