Problems with a user choosing a value outside the Enum range

I want the user to be able to enter a selection and that the program matches their selection using one of the parameters enum. I configured it in a loop, so the user can continue to try, if their record does not match (ie Apple, Banana, Carrots).

enum Food {Apple, Banana, Carrot};

Food foodChoice;
while (!(Enum.TryParse<Food>(Console.ReadLine(), true, out foodChoice)))
{
    Console.WriteLine("Not a valid choice.");
}

All this works fine and dandy until the user logs in, say 5. Obviously, there are Foodnot so many options in the enumeration , but TryParseit will still be displayed true, assigning foodChoiceto 5. Is there an easy way to handle this?

+4
source share
4 answers

- , .

Food foodChoice;
int n;
string temp;
while (!(Enum.TryParse<Food>(temp = Console.ReadLine(), true, out foodChoice)) || int.TryParse(temp,out n))
{
    Console.WriteLine("Not a valid choice.");
}
-1

Enum.IsDefined:

Food foodChoice;
while (!Enum.TryParse(Console.ReadLine(), true, out foodChoice)
    || !Enum.IsDefined(typeof(Food), foodChoice))
{
    Console.WriteLine("Not a valid choice.");
}
+7

MSDN ( ) TryParse:

, TEnum.... , TEnum, , . , IsDefined, , TEnum.

, , , , , IsDefined :

!Enum.IsDefined(typeof(Food), foodChoice)

? . , . , :

Food foodChoice = Food.Carrot|Food.Apple|Food.Banana;

, 5 . . .

+4

:

    var x = Enum.GetValues(typeof(Food));
    var a = Enum.IsDefined(typeof(Food), "Apple");
    var b = Enum.IsDefined(typeof(Food), "2");
    var c = Enum.IsDefined(typeof(Food), 2);
    var d = Enum.IsDefined(typeof(Food), 4);
    var e = Enum.GetNames(typeof(Food)).Contains("Apple");
    var f = Enum.GetNames(typeof(Food)).Contains("2");
    //var f = Enum.GetNames(typeof(Food)).Contains(2); //won't compile...
0

Source: https://habr.com/ru/post/1615480/


All Articles