Recursive Anonymous Methods

Comments 0

Share to social media

I was having a lively discussion with a friend the other day on the finer points of anonymous methods and lambda expressions. Yes, at Cogent Company this is actually what we do for fun. I had basically said that an anonymous method was just like any other method, to which he rattled off a laundry list of the differences. One of those differences caught my attention: you cannot create a recursive anonymous method. At first glance it seems to make perfect sense – how can you call a method with no name.? But when you think about it from a CLR perspective, how could you not be able to? An anonymous method is basically like any other method, and if any other method can be called recursively then so can an anonymous method.

So, here’s the code for a recursive anonymous method that solves factorials:

using System;
using System.Reflection;

namespace RecursiveAnonymous
{
class Program
{
delegate int FactorialDelegate(int i);

static void Main(string[] args)
{
FactorialDelegate factMethod = x =>
{
return x <= 1 ? 1 : x * (int)MethodBase.GetCurrentMethod()
.Invoke(null, new object[] { x - 1 });
};
for (int i = 0; i < 10; i++)
{
Console.WriteLine(factMethod.Invoke(i));
}
Console.Read();
}
} //class
} //namespace

The real trick is to use MethodBase.GetCurrentMethod(), which gets a reference to the MethodBase of the currently executing method (essentially the MethodInfo). From there you can call the .Invoke method and pass in the appropriate parameters, allowing the anonymous method to execute again (recursively). Hooray for reflection.

I have no idea why anyone would want to do this, aside from settling bets or showing off, but it’s nice to know that you can. As for my buddy, he says I cheated. To which I can only reply, damn straight! 🙂

Load comments

About the author

Damon Armstrong

See Profile

Damon Armstrong is a consultant with SystemwarePS in Dallas, Texas. He is also a blogger and author of Pro ASP.NET 2.0 Website Programming and SharePoint 2013 Essentials for Developers. He specializes in the Microsoft stack with a focus on web technologies like MVC, ASP.NET, JavaScript, and SharePoint. When not staying up all night coding, he can be found watching a bunch of kids, studying Biblical topics, playing golf, or recovering from staying up all night coding.