Posted on Monday May 3, 2010

Delegates, Funcs and Actions by example

This is a small set of reference examples of the various ways of declaring delegates, funcs and actions across the different versions of the framework and C#. I haven’t included any examples of passing Funcs,Actions as method parameters and interogating them, but Jon Skeet has a good post on it, and this stackoverflow question also demonstrates Action based operations quite succinctly. None of this article is under-the-hood in depth stuff - just a simple reference.

I haven’t included Expressions and System.Linq.Expression - there’s a large MSDN article on Expression trees which is very detailed already. A great example usage of Expressions is found in Fluent NHibernate and the source for its ClassMap class.

Delegates

The Delegate class is the base class for delegate types. However, only the system and compilers can derive explicitly from the Delegate class

Func<TResult,..>

Func Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.

The biggest difference with Func and Action (introduced in .NET 3.5) and delegates, aside from removing delegate definition repetition, is you can declare your Func inside a method and aren’t restricted to declaring at a field level. From what I can tell and I maybe wrong, this restriction on non-field delegate definitions is to avoid confusion with the anonymous method (funcMethod2) way of doing inline delegates.

Action<T,..>

Action encapsulates a method that takes a single parameter and does not return a value.

Action was introduced in .NET 2.0 alongside helpers such as EventHandler that made a lot of repetitive delegate definitions redundant.