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 didn t find a solution

string input = Console.ReadLine(); string output = "";

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

        Console.WriteLine(output);
    }
Program.cs
using System;

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


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

            Console.WriteLine(output);
        }
    }
}

2 Answers

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

The problem is the variable is declared inside the if block, and then we're trying to access it outside of that block which is out of scope. The challenge wants us to declare the variable earlier, before we open the if block, so that it's in an outer scope. I'm declaring it on line 4, and then later on line 8 I reassign the value with output = "Goodbye." as opposed to declaring it for the first time with string output = "Goodbye":

static void Main()
        {            
            string input = Console.ReadLine();
            string output;

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

            Console.WriteLine(output);
        }

Thank you so much brother i understand you now