The below code snippet works perfectly and reverses the string
"abc"
, recursively, and gives us the correct output as "cba"
.
If the method ReverseString
was static
, instead of non-static
, we would have called the method ReverseString
from Main()
, without having to create an instance of Program
- and we would have simply called it as: string reversed = Program.ReverseString("abc");
In that scenario (when the method ReverseString
were static
), the method ReverseString
and all it's local variables would reside on the Stack-memory and, Activation Records (call stacks) for ReverseString
would build up on the Stack-memory.
But for the case when ReverseString
is non-static, and we instantiate the class Program
, the non-static
method ReverseString
would lie on the Heap. And when we do prog.ReverseString
, the pointer prog
on the Stack will call the method ReverseString
on the Heap. And ReverseString
on the Heap will call itself in a recursive way on the Heap. Is my understanding correct? I believe I am wrong when I say recursion is happening on the Heap, in the below code snippet. I will be highly grateful, if you could tell me what exactly goes on the Stack and the Heap, in the code snippet below. And what would go on the Stack and the Heap if ReverseString
were static
and we called ReverseString
from Main()
as: string reversed = Program.ReverseString("abc");
internal class Program
{
static void Main(string[] args)
{
Program prog = new Program();
string reversed = prog.ReverseString("abc");
}
public string ReverseString(string input)
{
if (input == string.Empty)
return string.Empty;
else return ReverseString(input.Substring(1)) + input[0];
}
}