Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the integer value of an enum, when i only have the type of the enum

Tags:

c#

enums

I think this question needs some code:

private TypeValues GetEnumValues(Type enumType, string description)
        {
            TypeValues wtv = new TypeValues();
            wtv.TypeValueDescription = description;
            List<string> values = Enum.GetNames(enumType).ToList();
            foreach (string v in values)
            {
                //how to get the integer value of the enum value 'v' ?????
                wtv.TypeValues.Add(new TypeValue() { Code = v, Description = v });
            }
            return wtv;

        }

Call it like this:

GetEnumValues(typeof(AanhefType), "some name");

In the GetEnumValues function i have the values of the enum. So i iterate the values and i want to get the integer value of that enum value also.

So my values are 'red' and 'green', and i also want to get 0 and 1.

When i have the Enum in my function, i can create the enum value from the string and cast it to that enum and then cast it to an int, but in this case, i don't have the enum itself, but only the type of the enum.

I tried passing in the actual enum as a parameter too, but i'm not allowed to pass an enum as a parameter.

So now i'm stuck.....

like image 503
Michel Avatar asked Dec 27 '22 19:12

Michel


2 Answers

private TypeValues GetEnumValues(Type enumType, string description)
        {
            TypeValues wtv = new TypeValues();
            wtv.TypeValueDescription = description;
            List<string> values = Enum.GetNames(enumType).ToList();
            foreach (string v in values)
            {
                //how to get the integer value of the enum value 'v' ?????

               int value = (int)Enum.Parse(enumType, v);

                wtv.TypeValues.Add(new TypeValue() { Code = v, Description = v });
            }
            return wtv;

        }

http://msdn.microsoft.com/en-us/library/essfb559.aspx

Enum.Parse will take a Type and a String and return a reference to one of the enum values - which can then simply be cast to int.

like image 132
Steve Avatar answered Jan 12 '23 00:01

Steve


Try

(int)Enum.Parse(enumType, v)
like image 30
Sergey Berezovskiy Avatar answered Jan 11 '23 23:01

Sergey Berezovskiy