There is such a thing called tail recursive optimization.
From a stack perspective, basically it means that if the last thing an method does is call another method, the new call can take the stack frame of the calling method. For example in:
static void Main()
{
fn(0);
}
static void fn(int value)
{
fn(value+1);
}
instead of the call stack growing Main->fn(0)->fn(1)->...
ad nauseam, it will be at exactly two links long, first Main->fn(0)
than Main->fn(1)
, up to Main->fn(int.MaxValue)
where it will either blow up or overflow.
Now, the question is, does the C# compiler actually does this?
AFAIK, using the 4.0 and later C# compilers, when compiling in a x86 environment, it does not use tail-call optimization, and when compiling x64 application, it does use tail-call optimization (and apparently, from the other comments/answers I'm correct). E.g. On my system, using LINQPad, the code you provided promptly blew up with a StackOverflowException
.