How to recursively call a Lambda Expression

Have you ever faced the below situation where C# does not allow you to recursively call a lambda expression?

For example, if you try the below code, you will realize that it doesn’t work.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Action<string> someString = (input) =>
                {
                    if (input == "Initial Value")
                    {
                        System.Console.WriteLine(input);
                        someString("New Value");
                    }
                    else
                    {
                        System.Console.WriteLine(input);
                    }
                };

            someString("Initial Value");

            System.Console.ReadLine();
        }
    }
}

It will give you an error saying “Use of unassigned local variable 'someString'”.

There is a simple enough explanation for this. The variable is being initialized in the declaration itself. So, when it is used within the delegate, it is not yet initialized and this is not allowed in C#.

This can be easily rectified by splitting the declaration and assignment into two separate statements as shown below, so that when it is used within the delegate, the variable already has a value as shown below.

    System.Action<string> someString = null;

    someString = (input) => …