Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,354 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();