C# – How to Cast Int to Enum

c++castingenumsinteger

How do I cast an int to an enum in C#?

Best Answer

From an int:

YourEnum foo = (YourEnum)yourInt;

From a string:

YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

// The foo.ToString().Contains(",") check is necessary for 
// enumerations marked with a [Flags] attribute.
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
    throw new InvalidOperationException(
        $"{yourString} is not an underlying value of the YourEnum enumeration."
    );
}

From a number:

YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);
Related Question