Q:

StackOverflowException on recursive anonymous functions

I'm trying to write a function to check whether a string is a palindrome, and using this example, I'm trying to reverse the string using a recursive anonymous function:
static Boolean checkPalindromeAnonRec(string str)
{
    str = str.ToLower().Replace(" ", String.Empty);
    Func<string, string> revStr = null;
    revStr = delegate(string s) 
      { 
        if (s.Length > 1) 
          { return revStr(s) + s[0]; } 
        else 
        { return s; } 
      };

    return (str == revStr(str));
}

But every time I run it I get a StackOverflowException. It's not obvious to me why, any ideas?

A:

Well this is the problem:
if (s.Length > 1) 
  { return revStr(s) + s[0]; } 

Aside from the odd bracing style, that's just recursing with the original string - so it will keep going forever. I suspect you meant to use Substring somewhere so that it recursed using a shorter string...
I would actually try writing it as a simple non-anonymous (but still recursive) method to start with - so work out how you would recursively write:
static string Reverse(string input)

... then if you still want to inline that into your CheckPalindrome method, you can do so.

