Categories
c# casting enums integer

How do I cast int to enum in C#?

3702

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

0

    4439

    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);
    

    16

    • 40

      @FlySwat, what if YourEnum is dynamic and will only be known at runtime, and what I want is to convert to Enum?

      Feb 19, 2012 at 9:56

    • 271

      Be aware that Enum.Parse will NOT work if your code is obfuscated. At run time after obfuscation the string is compared to the enum names, and at this point the names of the enums aren’t what you would expect them to be. Your parse will fail where they succeeded before as a result.

      – jropella

      Apr 26, 2013 at 18:03

    • 186

      BEWARE If you use the “from a string” syntax above and pass in an invalid string that is a number (e.g. “2342342” — assuming that’s not a value of your enum), it will actually allow that without throwing an error! Your enum will have that value (2342342) even though it’s not a valid choice in the enum itself.

      – JoeCool

      Jun 25, 2013 at 15:14

    • 156

      I think this answer is a bit dated now. For string, you should really be using var result = Enum.TryParse(yourString, out yourEnum) nowadays (and checking the result to determine if the conversion failed).

      Nov 26, 2013 at 21:40

    • 25

      It is also possible to have Enum.Parse be case-insensitive by adding a true parameter value to the call: YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString, true);

      Feb 5, 2014 at 12:18

    1062

    Just cast it:

    MyEnum e = (MyEnum)3;
    

    Check if it’s in range using Enum.IsDefined:

    if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }
    

    7

    • 237

      Beware you can’t use Enum.IsDefined if you use the Flags attribute and the value is a combination of flags for example: Keys.L | Keys.Control

      – dtroy

      Jul 31, 2009 at 4:49

    • 19

      Regarding Enum.IsDefined, be aware that it can be dangerous: msdn.microsoft.com/en-us/library/ms229025(VS.90).aspx

      – adrian

      Dec 4, 2013 at 11:26

    • 4

      I prefer this definition: “Returns an indication whether a constant with a specified value exists in a specified enumeration” from MSDN

      – Pap

      Aug 18, 2014 at 19:13


    • 4

      …Because your definition can be misleading, because you are saying: “…check if it’s in range…” which implies within a range of numbers with starting and ending limits…

      – Pap

      Aug 18, 2014 at 19:20

    • 3

      @mac9416 I’ve tried to give a succinct example at gist.github.com/alowdon/f7354cda97bac70b44e1c04bc0991bcc – basically by using IsDefined to check input values, you leave yourself vulnerable to people adding new enum values later which would pass an IsDefined check (since the new value exists in the new code), but which might not work with the original code you wrote. It’s therefore safer to explicitly specify the enum values that your code is able to handle.

      – adrian

      Nov 12, 2018 at 22:43

    268

    Alternatively, use an extension method instead of a one-liner:

    public static T ToEnum<T>(this string enumString)
    {
        return (T) Enum.Parse(typeof (T), enumString);
    }
    

    Usage:

    Color colorEnum = "Red".ToEnum<Color>();
    

    OR

    string color = "Red";
    var colorEnum = color.ToEnum<Color>();
    

    5

    • 9

      For processing user input, it’s probably a good idea to call the overload of Enum.Parse that is allows you to specify that the comparison NOT be case sensitive (i.e. a user typing “red” (lowercase) would crash the above code without this change.)

      Jun 4, 2013 at 20:56

    • 13

      Handy, but the question specifically asks about ints.

      – BJury

      May 27, 2015 at 10:18

    • 3

      this also works if the string is an integer, e.g. “2”

      – TruthOf42

      Oct 6, 2016 at 19:19

    • 3

      This will throw an exception if enumString is null (had a similar issue yesterday). Consider using TryParse instead of Parse. TryParse will also check if T is an Enum Type

      – Justin

      Oct 18, 2016 at 15:03

    • 1

      This type of extension method on System.String seems like namespace pollution

      May 13, 2019 at 20:13