#1,190 – A Lambda Expression Can Be Recursive

A lambda expression can be recursive.  That is, it can invoke the same delegate that the lambda is being assigned to.  As with any recursive method, you need to make sure that there is termination logic to prevent the recursion from continuing indefinitely.

Below is an example of a simple recursive lambda expression.

            // Must assign delegate so that we can
            // reference it in lambda
            Action<int> countdown = null;
                
            countdown = (i) =>
            {
                if (i > 0)
                { 
                    Console.WriteLine(i);
                    countdown(i-1);
                }
            };

            countdown(5);

1190-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,190 – A Lambda Expression Can Be Recursive

  1. Pingback: Dew Drop – September 25, 2014 (#1863) | Morning Dew

Leave a comment