How do I cast an int
to an enum
in C#?
C# – How to Cast Int to Enum
c++castingenumsinteger
Related Solutions
Guessing about 'why' is always dangerous, but consider this:
enum Direction { North =1, East = 2, South = 4, West = 8 }
Direction ne = Direction.North | Direction.East;
int value = (int) ne; // value == 3
string text = ne.ToString(); // text == "3"
When the [Flags]
attribute is put in front of the enum, that last line changes to
string text = ne.ToString(); // text == "North, East"
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.)
Best Answer
From an int:
From a string:
From a number: