Search code examples
c#inputswitch-statementcasecontinuous

Continuous input to switch case until i press exit c#


I am trying to create a program where the application should never exit until I press option '6'. Below is my sample program: Right now, if I press any option, it executes the corresponding method and console window closes (exits the application) after it is done executing. I want the console to wait for the next option to be entered.

Console.WriteLine(@"Select one of the following option:                                
                            1-Write Apps 
                            2-Write Drivers
                            3-Write OS
                            4-Write Packages
                            5-All the above
                            6-Exit");
           string strReadKey = Console.ReadKey().KeyChar.ToString();

           int.TryParse(strReadKey, out selectionKey);


           switch (selectionKey)
           {

               case 1:
                   DoApps(reqObj);
                   return;
               case 2:
                   DoDrivers(reqObj);
                   return;
               case 3:
                   DoOS(reqObj);
                   return;
               case 4:
                   DoPackages(reqObj);
                   return;
               case 5:
                   DoAll(reqObj);
                   return;
               case 6:
                   Environment.Exit(0);                       
                   return;
               default:
                   DoAll(reqObj);
                   return;
           }

Solution

  • using System;
    
    namespace LoopUntilSelectionTester
    {
        class Program
        {
            static void Main()
            {            
                string key;
                while((key = Console.ReadKey().KeyChar.ToString()) != "6")            
                {
                    int keyValue;                
                    int.TryParse(key, out keyValue);
    
                    ProcessInput(keyValue);
                }    
            }
    
            private static void ProcessInput(int keyValue)
            {
                switch (keyValue)
                {
                    case 1:
                        DoApps(reqObj);
                        break;
                    case 2:
                        DoDrivers(reqObj);
                        break;
                    case 3:
                        DoOS(reqObj);
                        break;
                    case 4:
                        DoPackages(reqObj);
                        break;
                    case 5:
                        DoAll(reqObj);
                        break;
                }
            }
        }
    }