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?
Best Answer
You could also cast your value to
object
first and then toint
.###C# 7.3 and above
With the
Enum
generic constraint.###Below C# 7.3
Without the
Enum
generic constraint.If your enum inherits from other types for example from
byte
the cast toint
will throw anInvalidCastException
.You could either check if the base type of the enum is an integer.
Or you if you use
Convert.ToInt32
it will use theIConvertible
interface of int32 to convert the incompatible types.Just be aware the converting
uint
toint
and signed/unsigned pairs can cause unintended behavior. (Boxing toIConvertible
and the converting is less performant than just unboxing.)