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

152
Visualizações
If or switch? Which of these is a cleaner, more conventional code?

I learned, that if you can use switch cases, you should use them, because they are better in performance. Which one of the following code snippets would be more conventional? And how many cases that behave exactly the same are still ok for switch statements and when should you start using if statements?

        Console.Write("Insert a card value: ");
        int value = Int32.Parse(Console.ReadLine());
        string symbol = "";
        switch(value)
        {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 9:
            case 10:
                symbol = Convert.ToString(value);
                break;
            case 11:
                symbol = "J";
                break;
            case 12:
                symbol = "Q";
                break;
            case 13:
                symbol = "K";
                break;
            case 14:
                symbol = "A";
                break;
        }
        Console.WriteLine("The " + symbol + " has a value of " + value);

Or maybe this one?

    Console.Write("Insert a card value: ");
    int value = Int32.Parse(Console.ReadLine());
    string symbol = "";
    if (value <= 10)
        symbol = Convert.ToString(value);
    else if (value == 11)
        symbol = "J";
    else if (value == 12)
        symbol = "Q";
    else if (value == 13)
        symbol = "K";
    else if (value == 14)
        symbol = "A";
    Console.WriteLine("The " + symbol + " has a value of " + value);
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Starting from C#9, there is a new pattern matching which makes the switch very well readable:

string symbol = value switch
{
     >=1 and <=10 => Convert.ToString(value),
     11 => "J",
     12 => "Q",
     13 => "K",
     14 => "A",
     _ => ""
};

Online demo: https://dotnetfiddle.net/tovo7d

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