20090320

We got the Func<>

Another keyword in C# that always takes me by surprise is Func. To know what Func<> is for, we have to know what delegates are for. Delegates are a way to declare a function instance as a variable and pass it around, or make a list out of a set of them. Say we make a function that accepts a double as a parameter and returns a double.
private double Square(double squareThis)
{
  return Math.Pow(squareThis, 2.0);
}
private double Cube(double cubeThis)
{
  return Math.Pow(cubeThis, 3.0);
}
Next, we declare a delegate type to carry them around.
private delegate double MathFunc(double x);
Now, we can make a list of MathFunc delegates and execute them all in a loop.
var FuncList = new List
  {
      Square,
      Cube,
      x => x*10
  };
foreach (var func in FuncList)
{
  Console.WriteLine(func(3));
}
The last element is a lambda expression. There's no need to define the function in advance with C# 3.0. Now we can talk about the Func<>. Specifying Func<> means you're using a generic delegate, so that you don't have to declare the delegate elsewhere. The first type you specify between the brackets is the return type, and the rest are the parameter types. This code does the same thing as the last block, but doesn't use the MathFunc delegate. Func<> is the underlying type of the lambda expression. It was created to make predicate lambda expressions possible in LINQ.
var NewFuncList = new List>
  {
      Square,
      x => x*8
  };
foreach (var func in NewFuncList)
{
  Console.WriteLine(func(4));
}
Finally, Action<> is just a Func<> that doesn't have any return types, just parameters.

1 comments:

  1. I know what you mean, Func<> always takes me by surprise. What types of parameter will it support?

    ReplyDelete