Search code examples
c#enumscastinginteger

How do I cast int to enum in C#?


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


Solution

  • 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."
        );
    }
    

    Dynamically (type not known at compile-time):

    Type enumType = ...;
    
    // NB: Enums can specify a base type other than 'int'
    int numericValue = ...;
    
    object boxedEnumValue = Enum.ToObject(enumType, numericValue);