In C# 3.0 there are some new features such as lambda expressions we can find mostly in a functional languages. But when I tried some functional-like possibilities of version 3.0 I was quite dispapointed because I couldn’t declare recursive functions.
So what was the problem? Lets look at this implementation of factorial function int -> int (takes one int and returns int) using C# 3.0 lambda expressions:
Test 1
Func<int, int> fac = x => x == 0 ? 1 : x + fac(x - 1)
This is an optimal solution which unfortunatelly doesn’t work, we get an error message “Use of unassigned local variable ‘fac’“. We can’t use recursive calls like this, because compiler complains that fac is not declared when used.
Test 2
Lets try to declare fac function one line before:
Func<int, int> fac;
fac = x => x == 0 ? 1 : x + fac(x - 1);
Again, same error “Use of unassigned local variable ‘fac’”
Test 3
Func<int, int> fac = null;
fac = x => x == 0 ? 1 : x + fac(x - 1);
Now it works! If you want to use recursive calls inside function you have to declare and assign null before body declaration. However here we can see that C# 3.0 doesn’t allow us to write sexy-one-line code like in a first test case.