In the code below, when I examine the Chars variable while stepping through the code in the debugger, the size of the char array is 0 before the return line in the last iteration, but after the return line its 1 and continues growing back to the original size.
Why is this happening? thanks for any help in advance.
static void Main(string[] args)
{
string str = "Hello";
PrintReverse(str.ToArray()); // prints "olleH"
Console.Read();
}
static void PrintReverse(char[] Chars)
{
Console.Write(Chars[Chars.Length - 1]);
Array.Resize(ref Chars, Chars.Length - 1);
if (Chars.Length == 0) return;
PrintReverse(Chars);
}
Think about the chain of execution. You are recursively calling the method that shrinks the array until you get to 0, then you return to the caller (the same method) so you are seeing the grow back to the original size as you traverse back up the call stack.
No extra logic is happening as a result of this, as the recursive call is the last call in the method, but you get to see the debugger end each call, which in turn had an array size 1 bigger than the call before it.
If you were to pass the array by reference instead, however, the array size would remain at size 0 as it came up the call stack because each successive call to Array.Resize would create a new array and update all of the references to the new array instead of only the reference local to that call. (where as if you don’t pass by reference it updates only a copy of the reference, and does not update those in the calls before it).
This is because Array.Resize creates a new array and updates the reference to point to the new array instead of the old array, and by not passing by reference, you are sending a copy of the reference to the original array instead of the actual reference to the array, thus the calls to Array.Resize do not update the old references.
Thanks Groo for correcting me, hopefully I have it right this time