Recursive Anonymous Methods

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! 🙂