2

How do I get the value of an enum through input?

enum Planets
{
   Mercury = 0,
   Venus,
   Earth
}

I want something like when a user inputs a string for example I get the Enum integer Value of that input.

UserInput: Mercury

Value: 0

I did something like this:

Console.WriteLine("Value: "+(Planets)UserInput);

and as you can guess it won't compile.

Gashio Lee
  • 119
  • 1
  • 15
  • I think you want to parse the enum. See for example https://stackoverflow.com/questions/8922930/net-custom-configuration-how-to-case-insensitive-parse-an-enum-configurationpro – Michiel Leegwater Jul 20 '19 at 07:52

2 Answers2

2
var planet = (Planets)Enum.Parse(typeof(Planets), UserInput);
int planetNumber = (int)planet;
joehoper
  • 404
  • 3
  • 5
1

First, you have to cast your input string into an enum of your choice. That can be done with Enum.Parse(Type, String):

Planets planet = Enum.Parse(typeof(Planets), "Mercury")

Then you need to get the numerical value from the enum, which is a simple cast to integer:

int value = (int)planet;

Be careful with the first step: if the user inputs a string that is not valid, you'll get an exception which you'll have to handle. To avoid that you can use the Enum.TryParse() method which return a bool indicating the success of the action and pass the resulting enum as an out parameter.

Planets result;
bool success = Enum.TryParse<Planets>("Mars", true, out result);
if(success){
    Console.Write((int)result);
} else {
    Console.Write("no match");
}
pappbence96
  • 1,164
  • 2
  • 12
  • 20