C#: Recursive functions with Lambdas

Andreas Grech picture Andreas Grech · Jul 3, 2009 · Viewed 7.6k times · Source

The below does not compile:

Func<int, int> fac = n => (n <= 1) ? 1 : n * fac(n - 1);

Local variable 'fac' might not be initialized before accessing

How can you make a recursive function with lambdas?

[Update]

Here are also two links that I found interesting to read:

  1. Eric Lippert's "Why does a recursive lambda cause a definite assignment error?"
  2. Anonymous Recursion in C#

Answer

JaredPar picture JaredPar · Jul 3, 2009

This particular style of function is not supported by C# as a single line declaration. You have to separate out the declaration and definition into 2 lines

Func<int, int> fac = null;
fac = n => (n <= 1) ? 1 : n * fac(n - 1);