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

I don't understand what I am asked to do

What do I exactly remove?

Program.cs
using System;

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

            if (input == "")
            {

            }
            else 
            { 
            }

            Console.WriteLine(output);
        }
    }
}
Thor Giversen
Thor Giversen
771 Points

Here is the solution. You need to declare the string output outside of the scope of the if-statement and the else-statement. Then you can use the if-statement and the else-statement to assign the correct value to output.

In the code provided by treehouse the string output only exist inside the scope of the if/else statements. That means that when the Console.WriteLine() executes the string variable called output doesnΒ΄t exist anymore.

If you are still not clear on why that is you might benefit from reviewing the difference between local/global variables.

Hope this helps, and good luck :)

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {            
            string input = Console.ReadLine();
            string output = string.Empty;
            if (input == "quit")
            {
                output = "Goodbye.";
            }
            else
            {
                output = "You entered " + input + ".";
            }

            Console.WriteLine(output);
        }
    }
}

1 Answer

Brendo Brownley
Brendo Brownley
3,059 Points

So one other thing you'll want to fix... In this context, the if statement is being used to see if the user is entering the word "quit", or a different input. So you want to do

if (input == "quit")

to see whether or not the input equals that. If it does, we're setting the variable output to "Goodbye.", otherwise we remind what the user inputted by doing:

output = "You entered " + input + ".";

So restart the challenge. You want to declare the string output outside of the if statement, and remove any string declarations inside the if statement by simply deleting the keyword "string", because that string has already been declared. I hope this helps, if you have any other questions let me know :)