How do I cast a generic enum to int?
Solution 1:
You could also cast your value to object
first and then to int
.
C# 7.3 and above
With the Enum
generic constraint.
public static int EnumToInt<TValue>(this TValue value) where TValue : Enum
=> (int)(object)value;
Below C# 7.3
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.
Solution 2:
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
..........
..........
}
}
}