0

I'm new to C# and am making a text based game. Upon finishing it up, I've learned that gotos are the spawn of Satan (pffft). I have a lot of instances in this script where I ask the player a yes or no question, and if the player inputs anything else, they get an error message and I loop back to the start of the switch using a goto and a label. So given the example below, what would be a way to rework this code to produce the same results without using a goto? Thank you!

public static void One()
        {
            string response;

            Console.BackgroundColor = ConsoleColor.Red;
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Clear();
            Console.WriteLine("Some text.");
            OneOne:
            Console.ReadKey();
            Console.Write("\nA question?");
            response = Console.ReadLine().ToLower();
            Console.Clear();
            switch (YesOrNoDetector.Detect(response))
            {
                case YesOrNo.Yes:
                    {
                        Console.WriteLine("A response!");
                        Console.ReadKey();
                        Two();
                        break;
                    }
                case YesOrNo.No:
                    {
                        Console.WriteLine("A different response.");
                        Console.ReadKey();
                        Three();
                        break;

                    }
                case YesOrNo.Undefined:
                    {
                        Console.WriteLine("Refresh switch to look for a yes/no answer");
                        goto OneOne;
                    }
            }
        }
labmate
  • 37
  • 4
  • 1
    I give you the the `while` Loop. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements#the-while-statement – TheGeneral Aug 18 '21 at 04:20
  • 2
    You have the solution in your question _"if the player inputs anything else, they get an error message and I loop back to the start of the switch"_. Read up on how `while` and `do/while` loops work. You want to write a simple loop that you break out of when you get a valid answer. For what it's worth "Gotos are considered harmful" (https://homepages.cwi.nl/~storm/teaching/reader/Dijkstra68.pdf), not necessarily the spawn of Satan – Flydog57 Aug 18 '21 at 04:22

1 Answers1

4
//OneOne:
var haveValidAnswer = false;
while (! haveValidAnswer)
{
   Console.ReadKey();
  
   ... // as before, but with control of haveValidAnswer 

}

You should learn to design control flow without gotos. One problem is that goto logic is usually easy to write but a lot harder to read and maintain.

H H
  • 263,252
  • 30
  • 330
  • 514