Func and Action

suggest change

Func holds a method that returns a value. The leading type arguments are the inputs, and the last type argument is the return value.

// square a number.
Func<double, double> square = (x) => { return x * x; };

// get the square root.
// note how the signature matches the built in method.
Func<double, double> squareroot = Math.Sqrt;

// provide your workings.
Func<double, double, string> workings = (x, y) =>
    string.Format("The squares of {0} and {1} are {2} and {3}.", x, y, square(x), square(y));

Action holds a method that does not return a value, so its type arguments are only inputs. square and squareroot below are the delegates from the previous snippet.

// right-angled triangle.
class Triangle
{
    public double a;
    public double b;
    public double h;
}

// Pythagorean theorem.
Action<Triangle> pythagoras = (x) => 
    x.h = squareroot(square(x.a) + square(x.b));

Triangle t = new Triangle { a = 3, b = 4 };
pythagoras(t);
Console.WriteLine(t.h); // 5.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents