5

C# Homework question: I just added some "play again" logic using a do-while loop. This was my original code:

namespace demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Info myInfo = new Info();
            myInfo.DisplayInfo("Daniel Wilson", "4 - Hi-Lo Game");
               // I moved  String playAgain = "N"; to here 
            do
            {
                DWHiLowUI theUI = new DWHiLowUI();
                theUI.Play();
                String playAgain = "N";
                Console.WriteLine("Enter 'Y' to play again, any other key to exit.");
                playAgain = Console.ReadLine();
            }
            while ((playAgain == "Y")||(playAgain =="y"));
            Console.ReadLine();
        }
    }
}

Which gave me an error:

Error   7   The name 'playAgain' does not exist in the current context

I moved String playAgain = "N"; to the line ABOVE my do (see comment) and it worked fine.

I'm trying to understand what exactly I did to fix this. It seems like it was a scope issue, but it also seems to me that defining a variable within a loop could conceivably pass it to the end of the loop. I've looked through my textbooks, and there's not anything about scope as it relates to loops. That would suggest to me that scope within loops isn't an issue, but this is behaving as if it were a scope issue. I'm confusing myself thinking about it.

If it was a scope issue I'd like to have a better understanding of the scope of do...while loops within a method. If it wasn't a scope issue, it was a lucky guess on my part. In that case what was wrong and how did moving that line of code fix it?

dwwilson66
  • 6,806
  • 27
  • 72
  • 117

3 Answers3

8

You're correct, this is a scoping issue. C# has block scope which means that variables declared inside a block (code declared between {}) are only accessible inside of that block (and child blocks).

Since playAgain is defined inside of the loop body, it is not accessible outside of that block, not even within the while expression.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
6

Yes, it was the scope issue. The scope around do..while works like following

// outer scope
do 
{
    // inner scope
} while (/*outer scope*/);
// outer scope
hazzik
  • 13,019
  • 9
  • 47
  • 86
2

To Add on.. Each iteration of loop destroys the variables defined in that block, so when you are in the condition evaluation which is itself outside the block doesnot know what is playAgain that is defined in the inner context.

PSL
  • 123,204
  • 21
  • 253
  • 243