I always thought that if I used a switch statement and enter an option not specified the default would catch it. However, if I press enter then enter an option I get a run time error. How would I fix this? I am only including part of the code, if you want to see the rest I can post the rest.

public enum Options : byte
        {
            newZ = 1,
            display,
            Exit
        }
        static void displayMenu()
        {
            Console.WriteLine("Enter newZ to try new integers");
            Console.WriteLine("Enter display to see which Range Checker has the most Z's under the range");
            Console.WriteLine("Enter Exit to exit");
        }
        static void Main(string[] args)
        {
            RangeChecker[] rangeChecker = new RangeChecker[20];
            Random random = new Random();
            const int SIZE = 20;
            
            initialize(rangeChecker, SIZE);
            order(rangeChecker,  SIZE);
           
            for (; ; )
            {
                displayMenu();
                string volString = Console.ReadLine();
                Options options = (Options)Enum.Parse(typeof(Options), volString);
                switch (options)
                {
                    case Options.newZ: 
                        addZ(rangeChecker, SIZE);
                        break;
                    case Options.display:
                        display(rangeChecker, SIZE);
                        break; 
                    case Options.Exit:
                        Console.WriteLine("Goodbye");
                        System.Environment.Exit(1);
                        break;
                    default: 
                        Console.WriteLine("entry must be addZ, display, or Exit");
                        break;

                }
            }

        }
    }
}

I tried using TryParse, but get a error in Visual Studio
Error 1 The name 'TryParse' does not exist in the current context
Copied and pasted the code from MSDN into Visual Studio and still got the same error

Although your idea is good, it is in general not a good idea to do it in a console app. Make the user input as short as possible here use 1 or a for newZ etc. Make a menu: type 1 for this 2 for that etc.
If I as user have to type "display" and I mistype it as "dispaly" I have to do it all over again thinking of myself I cannot type!

This should work:

public enum Options
        {
            newZ = 1,
            display,
            Exit
        }

        void Method2()
        {
            string volString = "1";            
            Options options = (Options)Enum.Parse(typeof(Options), volString);
            switch (options)
            {
                case Options.newZ:
                    {
                        break;
                    }
            }
        }

Edited 5 Years Ago by Mitja Bonca: n/a

This article has been dead for over six months. Start a new discussion instead.