Recursive call with anonymous function
Whether you want to generate a dynamic function, write a dynamic algorithm or want to handle delegate inline, anonymous functions have always been at your service. However one area where in anonymous function lacking is, making a recursive call. Since it does not have function signature it’s not possible to make recursive call, at lease not directly. This entry shows you how to achieve that by utilizing some reflection API. Yes reflection, it’s always been there as your lifeguard ;).
   To understand the concept lets first create a simple recursive function to find a triangle.
Code: public int Triangle(int n)
{
return (n==1) ? 1 : n + Triangle(n-1);
}
{
return (n==1) ? 1 : n + Triangle(n-1);
}
Now we will use anonymous function to find a triangle. Please notice the code. It performs following steps to achive recursion.
- First finds the current performing method using top frame in the StackTrace.
- And then invokes it.
Code:
public delegate int TriangleDelegate(int n); public static int AnonymousMethodTriangle(int n)
{
TriangleDelegate triangle = delegate(int n)
{
//Find Method
MethodBase method =
new StackTrace().GetFrame(0).GetMethod();
return (n == 1) ? 1 : n +
(int)method.Invoke(null,new object[]
{n-1});//Invoke Method
};
return triangle(n);
}
public delegate int TriangleDelegate(int n); public static int AnonymousMethodTriangle(int n)
{
TriangleDelegate triangle = delegate(int n)
{
//Find Method
MethodBase method =
new StackTrace().GetFrame(0).GetMethod();
return (n == 1) ? 1 : n +
(int)method.Invoke(null,new object[]
{n-1});//Invoke Method
};
return triangle(n);
}
Pretty simple huh….
November 3rd, 2006 at 8:58 am
No, I dont think so. If you must use anonymuos methods and want to do recursive call then you will have to go with this approach… There is no direct simple way to achive this.
November 7th, 2006 at 10:35 pm
Clever stuff but sorta defeats the purpose of setting up an anonymous function in the first place, wouldn’t you think?
Anonymous methods reduce the overhead of creating delegates and methods and also make for better readable and understandable code being placed in an in-line fashion.
Is there a die-hard situation that you’ve come across where you’ve needed this?
November 10th, 2006 at 3:06 am
Yes, I had to create dynamic functions but one of the function was required recursive calls. I was thinking about using strategy pattern, but was not possible because lots of client code was already written, and it was difficult to change that.
At that time this was the solution that came to my rescue.