#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

Advertisement

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: