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?
You could also cast your value to object
first and then to int
.
With the Enum
generic constraint.
public static int EnumToInt<TValue>(this TValue value) where TValue : Enum => (int)(object)value;
Without the Enum
generic constraint.
public static int EnumToInt<TValue>(this TValue value) where TValue : struct, IConvertible { if(!typeof(TValue).IsEnum) { throw new ArgumentException(nameof(value)); } return (int)(object)value; }
If your enum inherits from other types for example from byte
the cast to int will throw an InvalidCastException
.
You could either check if the base type of the enum is an integer.
public static int EnumToInt<TValue>(this TValue value) where TValue : Enum { if (!typeof(int).IsAssignableFrom(Enum.GetUnderlyingType(typeof(TValue)))) throw new ArgumentException(nameof(TValue)); return (int)(object)value; }
Or you if you use Convert.ToInt32
it will use the IConvertible
interface of int32 to convert the incompatible types.
public static int EnumToInt<TValue>(this TValue value) where TValue : Enum => Convert.ToInt32(value);
Just be aware the converting uint
to int
and signed/unsigned pairs can cause unintended behavior. (Boxing to IConvertible
and the converting is less performant than just unboxing.)
I recommend creating a method for each enum base type to ensure the correct result is returned.
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 .......... .......... } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With