Search code examples
c#enums

How do I cast a generic enum to int?


I have a small method that looks like this:

public void SetOptions<T>() where T : Enum
{
    int i = 0;
    foreach (T obj in Enum.GetValues(typeof(T)))
    {
        if (i == 0)
            DefaultOption = new ListItem(obj.Description(), obj.ToString());
        i++;
        DropDownList.Items.Add(new ListItem(obj.Description(), obj.ToString()));
    }
}

Basically, I populate a dropdown list from an enum. Description() is actually an extension method for enums, so T is definitely an enum.

However, I want to cast obj just as you would any enum to its index like this (int)obj, but I get an error saying I can't convert T to int. Is there a way to do this?


Solution

  • try this,

    public void SetOptions<T>()
    {
        Type genericType = typeof(T);
        if (genericType.IsEnum)
        {
            foreach (T obj in Enum.GetValues(genericType))
            {
                Enum test = Enum.Parse(typeof(T), obj.ToString()) as Enum;
                int x = Convert.ToInt32(test); // x is the integer value of enum
                            ..........
                            ..........
            }
        }
    }