c# - Enums: Retrieve enum value from enumeration name string -
this question has answer here:
- how should convert string enum in c#? 19 answers
the enum:
public enum enumname { gary = 1, dave = 2 }
the input:
string inputvalue = "gary";
what best way retrieve value enum string? i.e. return value 1.
you can use enum.parse
convert string enum, or enum.tryparse
if less sure of input.
(enumname)enum.parse(typeof(enumname), inputvalue)
you can convert enum underlying type, default int if unspecified, casting. :
(int)enum.parse(typeof(enumname), inputvalue)
Comments
Post a Comment