Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Basics (Retired) Perfect Variable Scope

not understanding what is going here

I am confused as to why this isn't working. are we supposed to try-catch for the input being quit? if so then what is to be the catch output?

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {            
            input = Console.ReadLine();

            if (input == "quit")
            {
                string output = "Goodbye.";
            }
            else
            {
                string output = "You entered " + input + ".";
            }

            Console.WriteLine(output);
        }
    }
}

1 Answer

Rune Andreas Nielsen
Rune Andreas Nielsen
5,342 Points

Hi Eli.

The problem in your code, is that your "output" variable is defined inside of a scope, so it cannot be printed on the last line.

using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {            
            input = Console.ReadLine();
            string output = "";

            if (input == "quit")
            {
                output = "Goodbye.";
            }
            else
            {
                output = "You entered " + input + ".";
            }

            Console.WriteLine(output);
        }
    }
}

So the thing i've changed in the code, is that i moved the "output" variable out of the if and else scopes, so it can be used on the last line with the console.writeline();