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

writting output variable

Hi,

I know that if I declare a variable within curly braces {} it exists only inside them so I called WriteLine(output) inside braces{} as well.

I didn't erased the output variable. I can't see what's my mistake.

Can you help please? Thank you :)

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {

            string input = Console.ReadLine();


            if (input == "quit")
            {
                string output = "Goodbye.";
                Console.WriteLine(output);

            }
            else
            {
                string output = "You entered " + input + ".";
                Console.WriteLine(output);
            }



        }
    }
}

2 Answers

Steven Parker
Steven Parker
231,210 Points

This might be considered changing "the intent or intended behavior of the code". But you have the right idea about the scope of "output".

Perhaps a better fix would be to just declare it in the same scope as the "WriteLine" statement.

Thanks for the tip Steven, you mean like this?

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

I tried but it didn't work

Steven Parker
Steven Parker
231,210 Points

I was suggesting that you might leave the "WriteLine" statement as it was supplied, but declare "output" before the conditional, and then in the conditional blocks do an ordinary assignment instead of an initialization.

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);
    }
}

}

This worked for me