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();
}
}
}

In the code listing I declared a function delegate. In the main procedure an instance of that delegate type is declared and assign to an anonymous delegate. The Anonymous method pulls itself of the stackframe and can recurs. Later (or anywhere) in the function the delegate instance can be used like any other function.

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.

Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]