You want a helper function. You are only using it from within a single function, and it likely uses variables and type parameters that are in scope in that containing function. On the other hand, unlike a lambda you don’t need it as a first class object, so you don’t care to give it a delegate type and allocate an actual delegate object. Also you may want it to be recursive or generic, or to implement it as an iterator.
To expand on it some more, the advantages are:
-
Performance.
When creating a lambda, a delegate has to be created, which is an unnecessary allocation in this case. Local functions are really just functions, no delegates are necessary.
Also, local functions are more efficient with capturing local variables: lambdas usually capture variables into a class, while local functions can use a struct (passed using
ref
), which again avoids an allocation.This also means calling local functions is cheaper and they can be inlined, possibly increasing performance even further.
-
Local functions can be recursive.
Lambdas can be recursive too, but it requires awkward code, where you first assign
null
to a delegate variable and then the lambda. Local functions can naturally be recursive (including mutually recursive). -
Local functions can be generic.
Lambdas cannot be generic, since they have to be assigned to a variable with a concrete type (that type can use generic variables from the outer scope, but that’s not the same thing).
-
Local functions can be implemented as an iterator.
Lambdas cannot use the
yield return
(andyield break
) keyword to implementIEnumerable<T>
-returning function. Local functions can. -
Local functions look better.
This is not mentioned in the above quote and might be just my personal bias, but I think that normal function syntax looks better than assigning a lambda to a delegate variable. Local functions are also more succinct.
Compare:
int add(int x, int y) => x + y; Func<int, int, int> add = (x, y) => x + y;