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.)