Casting int to enum in C#

HomeC#

Casting int to enum in C#

Sometimes you might come up with this, and the solution is simpler than what we thing The first way is If the value is coming from a string And dynamically, when you don’t know the type at compile time

Case insensitive comparison in C#
Implicit Index Access in C#
Convert DateTime to date in C#

Sometimes you might come up with this, and the solution is simpler than what we thing

The first way is

YourEnum foo = (YourEnum)yourInt;

If the value is coming 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."
    );
}

And dynamically, when you don’t know the type at compile time

Type enumType = ...;

// Enums can specify a base type other than 'int'
int numericValue = ...;

object boxedEnumValue = Enum.ToObject(enumType, numericValue);

COMMENTS

DISQUS: 0