Func square = x => x * x;
// for recursion, the variable must be fully
// assigned before it can be used, therefore
// the dummy null assignment is needed:
Func factorial = null;
factorial = n => n < 3 ? n : n * factorial(n-1);
Any of the following more verbose forms is possible, too: (I'm using square
as an example):
Func square = x => { return x * x; };
The expression is expanded to a statement block.
Func square = (double x) => { return x * x; };
Explicit parameter list instead of just one parameter with inferred type.
Func square = delegate(double x) { return x * x; };
This one uses the older "anonymous delegate" syntax instead of so-called "lambda expressions" (=>
).
P.S.: int
might not be an appropriate return type for a method such as factorial
. The above examples are only supposed to demonstrate syntax, so modify them as necessary.