c# - How to find enum value using dynamic enum name & enum key name? -


this question has answer here:

i know how find enum value if enum name & key known @ compile time. have situation enum name @ runtime. suggestion how achieve this.

using system;  namespace enumdemo {     internal class program     {         private static void main(string[] args)         {             string[] arritemnames = enum.getnames(typeof (enumclass.colors));             foreach (string itemname in arritemnames)             {                 console.writeline(                     "{0} = {1:d}", itemname,                     enum.parse(typeof (enumclass.colors), itemname));             }             console.writeline();              var enumval = getenumvalue("colors", "red");// here expecting 1             console.readkey();         }          //         public static int getenumvalue(string enumname, string itemname)         {             return 0;         }     }      public class enumclass     {         public enum colors { red = 1, green = 2, blue = 4, yellow = 8 };     } } 

note: enum inside class.

use enum.parse function , convert int described here

public static int getvalueof(string enumname, string enumconst) {     type enumtype = type.gettype(enumname);     if (enumtype == null)     {         throw new argumentexception("specified enum type not found", "enumname");     }      object value = enum.parse(enumtype, enumconst);     return convert.toint32(value); } 

if going call enum in subclass need in way:

public static void main() { {     console.writeline(getvalueof("yournamespace.enumclass+colors", "red")); } 

since know type use directly as:

public static void main() { {     console.writeline(getvalueof(typeof(enumclass.colors), "red")); }   public static int getvalueof(type enumtype, string enumconst) {     object value = enum.parse(enumtype, enumconst);     return convert.toint32(value); } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -