Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

446
Views
How to refactor this switch to eliminate GOTO?

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;
                    }
            }
        }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

//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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!