How can I cast int to enum?

Explanation

If you want to cast int to enum use:

So if you want to cast from an int:

YourEnum foo = (YourEnum)yourInt;

And if you want to cast from a string:

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

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

 

Update:

Also if you want a number you can also use:

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

 

Also read, grep a file, but show several surrounding lines?

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *