Friday, September 22, 2006
Recursive Nested Functions in C#
I was wondering today if it were possible to create nested functions. Procedures seem pretty straightforward: name an anonymous delegate and then invoke it later in the code using the name. But what about functions? Well, functions can be manage by declaring the delegate type first (shown in the example). What about recursive nested functions? Well, the name assigned to the delegate doesn't exist until after the anonymous delegate block. So, to recurs use reflection and pull the method right of the stack frame.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Diagnostics;
namespace NestedFunction
{
class Program
{
delegate long FactorialDelegate(long n);
static void Main(string[] args)
{
//recursive nested function - calculates Factorial(n)
FactorialDelegate Factorial = delegate(long n)
{
MethodBase method =
new StackTrace().GetFrame(0).GetMethod();
return n > 1 ? n * (long)method.Invoke(null,
new object[]{ n - 1 }) : n;
};
Console.WriteLine(Factorial(5));
Console.ReadLine();
}
}
}
Probably slow. Definitely heinous looking, but it does mean C# could support nested functions directly and you could use them now if you wanted to.
Subscribe to Posts [Atom]