Here’s my code
using System;
public class Program
{
public static void Method(int flowerInVase)
{
if (flowerInVase > 0)
{
Method(flowerInVase - 1);
Console.WriteLine(flowerInVase);
}
}
public static void Main()
{
Method(3);
}
}
I am interested in line Console.WriteLine(flowerInVase); the method calls itself until it’s terminated by the condition. And only after that when the stack is full it pops up each of the method from above and console writes the number starting from the least 1,2,3.
Why the console.writeline works only when stack pops up, why it ain’t writing the numbers on the way methods go to the termination, like 3,2,1? The compiler uses writeline only when it’s done doing recursion.
You’re getting 1,2,3 because of the way the lines in your
ifstatement are ordered.Main()callsMethod(3).Method(3)callsMethod(2)before it has a chance to print “3”. Execution immediately jumps to the top ofMethod; your first call toMethod, withflowersinvase=3, won’t complete until the recursive call does. Likewise,Method(2)immediately callsMethod(1), andMethod(1)callsMethod(0).Method(0)does nothing and returns toMethod(1), exactly where it left off; the next line is yourWriteLinecall, which prints “1” and then returns, which picks up the call toMethod(2)where it left off, printing “2”, and so on for “3”.You would only get “3,2,1” if the methods you called ran to completion before jumping to any methods they called recursively, which is not how C# works. The thing you have to remember about method calls is that once you call a method, execution jumps immediately to the start of the method you called; the code after the method call will not execute until the method returns.