简体   繁体   中英

Using an enum and a switch statement c#

I am using an enum as my options for a switch statement and it works. The problem is if the user enter a non valid option the program crashes. What should I add so that the default is used?

my enum class

    public enum Options : byte
    {
        Display = 1,
        Add,
        Toggle,
        Max,
        Mean,
        Medium,
        Exit
    }

in main my switch statement

    string volString = Console.ReadLine();
    Options options = (Options)Enum.Parse(typeof(Options), volString);
    // this is the line that is giving me the runtime error. Since other options are not found

in the enum the program crashes.

                switch (options)
                {
                    case Options.Display: //dispaly regular time

                    case Options.Toggle://toggle 

                    default:
                        Console.WriteLine("entry blah blah");
                        break;

Instead of Enum.Parse use Enum.TryParse ... this will return a boolean to say if the text can be converted into your enum. If it's true run your switch otherwise inform the user that they entered an invalid string.

Use Enum.TryParse instead:

Options options;

if(!Enum.TryParse(volString, out options)) {
    // It wasn't valid input.
}

How about:

Options value;
if(!Enum.TryParse(volString, out value)) // note implicit <Options>
    value = Options.SomeDefaultValue;

查看Enum.TryParse(...),您可以使用它来检查无效的字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM