Search code examples
c#visual-studio-2013consoleconsole-applicationconsole.writeline

Changing console color, gives me a Stackoverflow Exception


I use following methods for printing some text in a different color on console.

        private static void WriteUpdatedBookingDetails(string text)
        {
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            WriteUpdatedBookingDetails(text);
        }

when I execute WriteUpdatedBookingDetails() method from following code, it gives me an exception

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll)

        static void Main(string[] args)
        {
            ...
            // Exception occurred when I call this method. 
            WriteUpdatedBookingDetails("\n- - Reconciling Updated Bookings - -"); 
            ...
            }
        }

Solution

  • Your problem is that you used recursion. When you call this method, the foreground is first set to dark green. But as you can see here, you call the same method again! This forms an infinite loop!

    When the loop loops for a lot of times, your stack overflows. That's why a StackOverflowException occurs. I guess you actually want to call

    Console.WriteLine (text);
    

    So this is how your method should look like:

    private static void WriteUpdatedBookingDetails(string text)
    {
        Console.ForegroundColor = ConsoleColor.DarkGreen;
        Console.WriteLine(text);
    }
    

    Then, your method will not call itself, so no more recursion!