Friday, 16 October 2009

Func and Action

Func(TResult) is a delegate type that encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.
MSDN documentation states:
“You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have no parameters and must return a value.”
The documentation goes on to point out that if you need a delegate type that does not have a return type use Action instead.
There are 4 further delegate types related to Func(TResult):
  • Func(T, TResult)
  • Func(T1, T2, TResult)
  • Func(T1, T2, T3, TResult)
  • Func(T1, T2, T3, T4, TResult)
Each of these encapsulates a method that takes one or more parameters of various types and which returns TResult.
There are equivalent Action types for encapsulating delegates that do not have a return type.
This is all very interesting when you consider you can assign a lambda expression to a Func, e.g.
Func<int, int, int> function = (a,b) => a + b;
…and that you can also create an Expression from a lambda represented as a Func.
Expression<Func<int, int, int>> expression = (a,b) => a + b;
More to follow on Expression.
Friday, 16 October 2009,