Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

447
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda