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

Xinyu (Sean) Zhang
PLUS
Xinyu (Sean) Zhang
Courses Plus Student 7,064 Points

How to answer this question?

How to answer this question?

Program.cs
using System;

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

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

2 Answers

Steven Parker
Steven Parker
229,786 Points

:point_right: Here's a few hints:

  • you're trying to fix the code, not change functionality, so you won't need try or catch
  • check that all variables are declared before they are used (or at the same time they are initialized)
  • remember that a variable can be declared only once, but it may be assigned many times
  • check that all variables are declared in the widest scope in which they are used
  • be sure to use the preview button to see the complier errors for more hints

The issues is that output is created inside of the if statements which limits the variables scope to only being available inside the braces. To fix the issues, initialize the variable before the if statement and remove the initialization that's happening inside the if statement.

Console.WriteLine(output);