Friday, March 16, 2012

How to use the Func type in C#

To make using delegates easier, Microsoft introduced a new generic type, Func.

Main features:

  • The Func encapsulates callable code. 
  • It can take 1 to 16 input parameters.
  • The last prameter is the return type.
There, easy.

As an example, Func<int, int, bool> takes two integers as input and will return a bool.

private static void PlayWithFunc()
// First two params are input, last param is output
Func<int, int, int> addemup = (x,y) => x+y;
Console.WriteLine( addemup(2, 3));
// Note that with the single input param, x is in brackets: (x)
Func<int, bool> notZero = (x) => x!=0;
Console.WriteLine( notZero(1) );
// Note also,that with the single input param, x is NOT brackets: x
Func<int, int> sqr = x => x*x;
Console.WriteLine( sqr(2) );

Note that if you have 2 or more parameters in the lambda expression you must have parenthesis. If you have one parameter the parameters are optional.

Ah, but what happens if you don't want to return a value. 

The Action type is the same as Func, except it returns void.

Action <string> printToConsole = s => Console.WriteLine("The string is: " + s);

printToConsole ("Hi there");

No comments:

Post a Comment