How does scope factor into "do...while" loops and vice versa?

c#, loops, scope

Solution

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.

Problem

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?

Original source

Related problems