Local functions in C# 7 are versatile: they can be passed as Func<>
and Action<>
to other methods and they can be defined using the inline expression bodied syntax.
Because local functions are compiled into static methods, you should be able to pass them to any method that requires a Func<>
or Action<>
and sure enough you can. Here's an example to demonstrate:
private void test()
{
printResult(count);
int count(string input)
{
return input.Length;
}
}
private void printResult(Func<string, int> func)
{
Console.Out.WriteLine(func("Hello World!"));
}
Output:
12
Local functions can also be defined using the inline expression bodied syntax shown here:
private void test()
{
printResult(count);
int count(string input) => input.Length;
}
Obviously, you shouldn't use local functions in this way unless it makes sense. In this case, we could have written test
much more simply without local functions:
private void test()
{
printResult(input => input.Length);
}
Addendum
Update (19th April 2017): Marc Gravell pointed out to me that local functions are compiled to static methods, unless they access this
, in which case they're compiled to instance methods.