Local functions in C#
Functions can live inside the body that uses them.
// local functions live inside the surrounding body
int Square(int x) => x * x;
int SumOfSquares(int[] values)
{
var total = 0;
foreach (var v in values) total += Square(v);
return total;
}
var data = new[] { 1, 2, 3, 4 };
Console.WriteLine(Square(9));
Console.WriteLine(SumOfSquares(data));
How it works
int Square(int x) => x * x;declares one locally, expression-bodied.SumOfSquarescalls its sibling; nothing leaks outside the file.- In a top-level program this is the shortest path to a helper.
Keywords and builtins used here
SquareSumOfSquaresforeachinintnewreturnvar
The run, in numbers
- Lines
- 13
- Characters to type
- 293
- Tokens
- 80
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 53 seconds.
Step 2 of 3 in Methods, step 16 of 29 in Language basics.