mercredi 14 juillet 2021

Replacing if statements with switches in C# [closed]

Here I have a function that's called within a while loop. I'm pretty sure the code could be optimised with a switch statement but I just can't figure it out? Please help me tidy this code.

I'm new to coding using the ConsoleApp so I was just making a basic program that records your keys, which I was later going to use to create a GUI, navigated via arrow keys,

void ifcheck()
        {
            ConsoleKeyInfo key = Console.ReadKey();
            if (key.Key == ConsoleKey.Escape)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("eStopping.. (0x0)");
                power = false;
            }
            else if (key.Key == ConsoleKey.Enter)
            {
                Console.WriteLine("\n" + "[----" + "Enter" + "----" + " Was pressed]");
            }
            else if (key.Key == ConsoleKey.Spacebar)
            {
                Console.WriteLine("\n" + "[----" + "Spacebar" + "----" + " Was pressed]");
            }
            else if (key.Key == ConsoleKey.Tab)
            {
                Console.WriteLine("\n" + "[----" + "Tab" + "----" + " Was pressed]");
            }
            else
            {
                Console.WriteLine("\n" + "[----" + key.KeyChar + "----" + " Was pressed]");
            }            
        }

Aucun commentaire:

Enregistrer un commentaire