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

Harrison Court
Harrison Court
4,232 Points

I don't get this

I have no idea how to do this, I've looked over it again and again, but with no luck. Care to help.

Program.cs
using System;

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

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

            Console.WriteLine(output);
            }
            catch {
                Console.ReadLine();
            }
        }
    }
}

1 Answer

Stephan Olsen
Stephan Olsen
6,650 Points

You actually do not need to use the try-catch statement. The problem in this case, is that within the scope of the if and else statement, the program thinks you're initializing a new variable called string output. When you're initializing it within the scope, you can't use it outside of the scope. Instead you should declare your variables like this:

using System;

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

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

            Console.WriteLine(output);
        }
    }
}