0

The enum:

public enum EnumName
{
    Gary = 1,
    Dave = 2
}

The input:

string inputValue = "Gary";

What is the best way to retrieve the value from the enum for this string? I.e. return the value 1.

MattMcGowan
  • 117
  • 1
  • 6

1 Answers1

2

You can use Enum.Parse to convert a string to an enum, or Enum.TryParse if you are less sure of the input.

(EnumName)Enum.Parse(typeof(EnumName), inputValue)

You can convert any enum to its underlying type, the default is int if unspecified, by casting. Like this :

(int)Enum.Parse(typeof(EnumName), inputValue)
Xiaoy312
  • 14,292
  • 1
  • 32
  • 44