<p>How do I cast an <code>int</code> to an <code>enum</code> in C#?</p>

[{'answer_id': 29485, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 13, 'selected': True, 'text': '<p>From an int:</p>\n<pre><code>YourEnum foo = (YourEnum)yourInt;\n</code></pre>\n<p>From a string:</p>\n<pre><code>YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);\n\n// The foo.ToString().Contains(&quot;,&quot;) check is necessary for \n// enumerations marked with a [Flags] attribute.\nif (!Enum.IsDefined(typeof(YourEnum), foo) &amp;&amp; !foo.ToString().Contains(&quot;,&quot;))\n{\n    throw new InvalidOperationException(\n        $&quot;{yourString} is not an underlying value of the YourEnum enumeration.&quot;\n    );\n}\n</code></pre>\n<p>From a number:</p>\n<pre><code>YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);\n</code></pre>\n'}, {'answer_id': 29488, 'author': 'abigblackman', 'author_id': 2279, 'author_profile': 'https://Stackoverflow.com/users/2279', 'pm_score': 7, 'selected': False, 'text': '<p>Take the following example:<br /></p>\n\n<pre><code>int one = 1;\nMyEnum e = (MyEnum)one;\n</code></pre>\n'}, {'answer_id': 29489, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 10, 'selected': False, 'text': '<p>Just cast it:</p>\n<pre><code>MyEnum e = (MyEnum)3;\n</code></pre>\n<p>Check if it\'s in range using <a href="http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx" rel="noreferrer"><code>Enum.IsDefined</code></a>:</p>\n<pre><code>if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }\n</code></pre>\n'}, {'answer_id': 3166694, 'author': 'L. D.', 'author_id': 382143, 'author_profile': 'https://Stackoverflow.com/users/382143', 'pm_score': 6, 'selected': False, 'text': '<p>Sometimes you have an object to the <code>MyEnum</code> type. Like</p>\n<pre><code>var MyEnumType = typeof(MyEnum);\n</code></pre>\n<p>Then:</p>\n<pre><code>Enum.ToObject(typeof(MyEnum), 3)\n</code></pre>\n'}, {'answer_id': 3655831, 'author': 'Tawani', 'author_id': 61525, 'author_profile': 'https://Stackoverflow.com/users/61525', 'pm_score': 6, 'selected': False, 'text': '<p>Below is a nice utility class for Enums</p>\n\n<pre><code>public static class EnumHelper\n{\n    public static int[] ToIntArray&lt;T&gt;(T[] value)\n    {\n        int[] result = new int[value.Length];\n        for (int i = 0; i &lt; value.Length; i++)\n            result[i] = Convert.ToInt32(value[i]);\n        return result;\n    }\n\n    public static T[] FromIntArray&lt;T&gt;(int[] value) \n    {\n        T[] result = new T[value.Length];\n        for (int i = 0; i &lt; value.Length; i++)\n            result[i] = (T)Enum.ToObject(typeof(T),value[i]);\n        return result;\n    }\n\n\n    internal static T Parse&lt;T&gt;(string value, T defaultValue)\n    {\n        if (Enum.IsDefined(typeof(T), value))\n            return (T) Enum.Parse(typeof (T), value);\n\n        int num;\n        if(int.TryParse(value,out num))\n        {\n            if (Enum.IsDefined(typeof(T), num))\n                return (T)Enum.ToObject(typeof(T), num);\n        }\n\n        return defaultValue;\n    }\n}\n</code></pre>\n'}, {'answer_id': 5655038, 'author': 'Evan M', 'author_id': 603384, 'author_profile': 'https://Stackoverflow.com/users/603384', 'pm_score': 5, 'selected': False, 'text': "<p>If you have an integer that acts as a bitmask and could represent one or more values in a [Flags] enumeration, you can use this code to parse the individual flag values into a list:</p>\n\n<pre><code>for (var flagIterator = 0; flagIterator &lt; 32; flagIterator++)\n{\n    // Determine the bit value (1,2,4,...,Int32.MinValue)\n    int bitValue = 1 &lt;&lt; flagIterator;\n\n    // Check to see if the current flag exists in the bit mask\n    if ((intValue &amp; bitValue) != 0)\n    {\n        // If the current flag exists in the enumeration, then we can add that value to the list\n        // if the enumeration has that flag defined\n        if (Enum.IsDefined(typeof(MyEnum), bitValue))\n            Console.WriteLine((MyEnum)bitValue);\n    }\n}\n</code></pre>\n\n<p>Note that this assumes that the underlying type of the <code>enum</code> is a signed 32-bit integer. If it were a different numerical type, you'd have to change the hardcoded 32 to reflect the bits in that type (or programatically derive it using <code>Enum.GetUnderlyingType()</code>)</p>\n"}, {'answer_id': 7847875, 'author': 'MSkuta', 'author_id': 897609, 'author_profile': 'https://Stackoverflow.com/users/897609', 'pm_score': 6, 'selected': False, 'text': '<p>I am using this piece of code to cast int to my enum:</p>\n\n<pre><code>if (typeof(YourEnum).IsEnumDefined(valueToCast)) return (YourEnum)valueToCast;\nelse { //handle it here, if its not defined }\n</code></pre>\n\n<p>I find it the best solution.</p>\n'}, {'answer_id': 7968381, 'author': 'Ryan Russon', 'author_id': 999428, 'author_profile': 'https://Stackoverflow.com/users/999428', 'pm_score': 6, 'selected': False, 'text': '<p>If you\'re ready for the 4.0 <a href="http://en.wikipedia.org/wiki/.NET_Framework">.NET</a> Framework, there\'s a new <em>Enum.TryParse()</em> function that\'s very useful and plays well with the [Flags] attribute. See <em><a href="http://msdn.microsoft.com/en-us/library/dd783499.aspx">Enum.TryParse Method (String, TEnum%)</a></em></p>\n'}, {'answer_id': 8094628, 'author': 'Abdul Munim', 'author_id': 228656, 'author_profile': 'https://Stackoverflow.com/users/228656', 'pm_score': 8, 'selected': False, 'text': '<p>Alternatively, use an extension method instead of a one-liner:</p>\n\n<pre><code>public static T ToEnum&lt;T&gt;(this string enumString)\n{\n    return (T) Enum.Parse(typeof (T), enumString);\n}\n</code></pre>\n\n<p><strong><em>Usage:</em></strong></p>\n\n<pre><code>Color colorEnum = "Red".ToEnum&lt;Color&gt;();\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>string color = "Red";\nvar colorEnum = color.ToEnum&lt;Color&gt;();\n</code></pre>\n'}, {'answer_id': 15005854, 'author': 'Sébastien Duval', 'author_id': 1848457, 'author_profile': 'https://Stackoverflow.com/users/1848457', 'pm_score': 6, 'selected': False, 'text': '<p>For numeric values, this is safer as it will return an object no matter what:</p>\n\n<pre><code>public static class EnumEx\n{\n    static public bool TryConvert&lt;T&gt;(int value, out T result)\n    {\n        result = default(T);\n        bool success = Enum.IsDefined(typeof(T), value);\n        if (success)\n        {\n            result = (T)Enum.ToObject(typeof(T), value);\n        }\n        return success;\n    }\n}\n</code></pre>\n'}, {'answer_id': 20999570, 'author': 'gmail user', 'author_id': 344394, 'author_profile': 'https://Stackoverflow.com/users/344394', 'pm_score': 3, 'selected': False, 'text': '<p>Different ways to cast <strong>to and from</strong> <code>Enum</code></p>\n\n<pre><code>enum orientation : byte\n{\n north = 1,\n south = 2,\n east = 3,\n west = 4\n}\n\nclass Program\n{\n  static void Main(string[] args)\n  {\n    orientation myDirection = orientation.north;\n    Console.WriteLine(“myDirection = {0}”, myDirection); //output myDirection =north\n    Console.WriteLine((byte)myDirection); //output 1\n\n    string strDir = Convert.ToString(myDirection);\n        Console.WriteLine(strDir); //output north\n\n    string myString = “north”; //to convert string to Enum\n    myDirection = (orientation)Enum.Parse(typeof(orientation),myString);\n\n\n }\n}\n</code></pre>\n'}, {'answer_id': 21577017, 'author': 'Shivprasad Koirala', 'author_id': 993672, 'author_profile': 'https://Stackoverflow.com/users/993672', 'pm_score': 5, 'selected': False, 'text': '<p><img src="https://i.stack.imgur.com/s1rY9.png" alt="enter image description here"></p>\n\n<p>To convert a string to ENUM or int to ENUM constant we need to use Enum.Parse function. Here is a youtube video <a href="https://www.youtube.com/watch?v=4nhx4VwdRDk" rel="noreferrer">https://www.youtube.com/watch?v=4nhx4VwdRDk</a>  which actually demonstrate\'s with string and the same applies for int.</p>\n\n<p>The code goes as shown below where "red" is the string and "MyColors" is the color ENUM which has the color constants.</p>\n\n<pre><code>MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyColors), "Red");\n</code></pre>\n'}, {'answer_id': 22830894, 'author': 'atlaste', 'author_id': 1031591, 'author_profile': 'https://Stackoverflow.com/users/1031591', 'pm_score': 8, 'selected': False, 'text': '<p>I think to get a complete answer, people have to know how enums work internally in .NET. </p>\n\n<p><strong>How stuff works</strong></p>\n\n<p>An enum in .NET is a structure that maps a set of values (fields) to a basic type (the default is <code>int</code>). However, you can actually choose the integral type that your enum maps to:</p>\n\n<pre><code>public enum Foo : short\n</code></pre>\n\n<p>In this case the enum is mapped to the <code>short</code> data type, which means it will be stored in memory as a short and will behave as a short when you cast and use it. </p>\n\n<p>If you look at it from a IL point of view, a (normal, int) enum looks like this:</p>\n\n<pre><code>.class public auto ansi serializable sealed BarFlag extends System.Enum\n{\n    .custom instance void System.FlagsAttribute::.ctor()\n    .custom instance void ComVisibleAttribute::.ctor(bool) = { bool(true) }\n\n    .field public static literal valuetype BarFlag AllFlags = int32(0x3fff)\n    .field public static literal valuetype BarFlag Foo1 = int32(1)\n    .field public static literal valuetype BarFlag Foo2 = int32(0x2000)\n\n    // and so on for all flags or enum values\n\n    .field public specialname rtspecialname int32 value__\n}\n</code></pre>\n\n<p>What should get your attention here is that the <code>value__</code> is stored separately from the enum values. In the case of the enum <code>Foo</code> above, the type of <code>value__</code> is int16. This basically means that you can store whatever you want in an enum, <strong>as long as the types match</strong>.</p>\n\n<p>At this point I\'d like to point out that <code>System.Enum</code> is a value type, which basically means that <code>BarFlag</code> will take up 4 bytes in memory and <code>Foo</code> will take up 2 -- e.g. the size of the underlying type (it\'s actually more complicated than that, but hey...).</p>\n\n<p><strong>The answer</strong></p>\n\n<p>So, if you have an integer that you want to map to an enum, the runtime only has to do 2 things: copy the 4 bytes and name it something else (the name of the enum). Copying is implicit because the data is stored as value type - this basically means that if you use unmanaged code, you can simply interchange enums and integers without copying data.</p>\n\n<p>To make it safe, I think it\'s a best practice to <strong>know that the underlying types are the same or implicitly convertible</strong> and to ensure the enum values exist (they aren\'t checked by default!).</p>\n\n<p>To see how this works, try the following code:</p>\n\n<pre><code>public enum MyEnum : int\n{\n    Foo = 1,\n    Bar = 2,\n    Mek = 5\n}\n\nstatic void Main(string[] args)\n{\n    var e1 = (MyEnum)5;\n    var e2 = (MyEnum)6;\n\n    Console.WriteLine("{0} {1}", e1, e2);\n    Console.ReadLine();\n}\n</code></pre>\n\n<p>Note that casting to <code>e2</code> also works! From the compiler perspective above this makes sense: the <code>value__</code> field is simply filled with either 5 or 6 and when <code>Console.WriteLine</code> calls <code>ToString()</code>, the name of <code>e1</code> is resolved while the name of <code>e2</code> is not.</p>\n\n<p>If that\'s not what you intended, use <code>Enum.IsDefined(typeof(MyEnum), 6)</code> to check if the value you are casting maps to a defined enum.</p>\n\n<p>Also note that I\'m explicit about the underlying type of the enum, even though the compiler actually checks this. I\'m doing this to ensure I don\'t run into any surprises down the road. To see these surprises in action, you can use the following code (actually I\'ve seen this happen a lot in database code):</p>\n\n<pre><code>public enum MyEnum : short\n{\n    Mek = 5\n}\n\nstatic void Main(string[] args)\n{\n    var e1 = (MyEnum)32769; // will not compile, out of bounds for a short\n\n    object o = 5;\n    var e2 = (MyEnum)o;     // will throw at runtime, because o is of type int\n\n    Console.WriteLine("{0} {1}", e1, e2);\n    Console.ReadLine();\n}\n</code></pre>\n'}, {'answer_id': 24534466, 'author': 'LawMan', 'author_id': 2574087, 'author_profile': 'https://Stackoverflow.com/users/2574087', 'pm_score': 3, 'selected': False, 'text': '<p>In my case, I needed to return the enum from a WCF service.  I also needed a friendly name, not just the enum.ToString().</p>\n\n<p>Here\'s my WCF Class.</p>\n\n<pre><code>[DataContract]\npublic class EnumMember\n{\n    [DataMember]\n    public string Description { get; set; }\n\n    [DataMember]\n    public int Value { get; set; }\n\n    public static List&lt;EnumMember&gt; ConvertToList&lt;T&gt;()\n    {\n        Type type = typeof(T);\n\n        if (!type.IsEnum)\n        {\n            throw new ArgumentException("T must be of type enumeration.");\n        }\n\n        var members = new List&lt;EnumMember&gt;();\n\n        foreach (string item in System.Enum.GetNames(type))\n        {\n            var enumType = System.Enum.Parse(type, item);\n\n            members.Add(\n                new EnumMember() { Description = enumType.GetDescriptionValue(), Value = ((IConvertible)enumType).ToInt32(null) });\n        }\n\n        return members;\n    }\n}\n</code></pre>\n\n<p>Here\'s the Extension method that gets the Description from the Enum.</p>\n\n<pre><code>    public static string GetDescriptionValue&lt;T&gt;(this T source)\n    {\n        FieldInfo fileInfo = source.GetType().GetField(source.ToString());\n        DescriptionAttribute[] attributes = (DescriptionAttribute[])fileInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);            \n\n        if (attributes != null &amp;&amp; attributes.Length &gt; 0)\n        {\n            return attributes[0].Description;\n        }\n        else\n        {\n            return source.ToString();\n        }\n    }\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>return EnumMember.ConvertToList&lt;YourType&gt;();\n</code></pre>\n'}, {'answer_id': 24806564, 'author': 'Ted', 'author_id': 429973, 'author_profile': 'https://Stackoverflow.com/users/429973', 'pm_score': 5, 'selected': False, 'text': '<p>Slightly getting away from the original question, but I found <a href="https://stackoverflow.com/a/11057004/429973">an answer to Stack&nbsp;Overflow question <em>Get int value from enum</em></a> useful. Create a static class with <code>public const int</code> properties, allowing you to easily collect together a bunch of related <code>int</code> constants, and then not have to cast them to <code>int</code> when using them.</p>\n\n<pre><code>public static class Question\n{\n    public static readonly int Role = 2;\n    public static readonly int ProjectFunding = 3;\n    public static readonly int TotalEmployee = 4;\n    public static readonly int NumberOfServers = 5;\n    public static readonly int TopBusinessConcern = 6;\n}\n</code></pre>\n\n<p>Obviously, some of the enum type functionality will be lost, but for storing a bunch of database id constants, it seems like a pretty tidy solution.</p>\n'}, {'answer_id': 25045892, 'author': 'CZahrobsky', 'author_id': 888792, 'author_profile': 'https://Stackoverflow.com/users/888792', 'pm_score': 4, 'selected': False, 'text': '<p>This parses integers or strings to a target enum with partial matching in .NET 4.0 using generics like in <a href="https://stackoverflow.com/questions/29482/how-can-i-cast-int-to-enum/3655831#3655831">Tawani\'s utility class</a>. I am using it to convert command-line switch variables which may be incomplete.  Since an enum cannot be null, you should logically provide a default value.  It can be called like this:</p>\n<pre><code>var result = EnumParser&lt;MyEnum&gt;.Parse(valueToParse, MyEnum.FirstValue);\n</code></pre>\n<p>Here\'s the code:</p>\n<pre><code>using System;\n\npublic class EnumParser&lt;T&gt; where T : struct\n{\n    public static T Parse(int toParse, T defaultVal)\n    {\n        return Parse(toParse + &quot;&quot;, defaultVal);\n    }\n    public static T Parse(string toParse, T defaultVal)\n    {\n        T enumVal = defaultVal;\n        if (defaultVal is Enum &amp;&amp; !String.IsNullOrEmpty(toParse))\n        {\n            int index;\n            if (int.TryParse(toParse, out index))\n            {\n                Enum.TryParse(index + &quot;&quot;, out enumVal);\n            }\n            else\n            {\n                if (!Enum.TryParse&lt;T&gt;(toParse + &quot;&quot;, true, out enumVal))\n                {\n                    MatchPartialName(toParse, ref enumVal);\n                }\n            }\n        }\n        return enumVal;\n    }\n\n    public static void MatchPartialName(string toParse, ref T enumVal)\n    {\n        foreach (string member in enumVal.GetType().GetEnumNames())\n        {\n            if (member.ToLower().Contains(toParse.ToLower()))\n            {\n                if (Enum.TryParse&lt;T&gt;(member + &quot;&quot;, out enumVal))\n                {\n                    break;\n                }\n            }\n        }\n    }\n}\n</code></pre>\n<p><strong>FYI:</strong>  The question was about integers, which nobody mentioned will also explicitly convert in Enum.TryParse()</p>\n'}, {'answer_id': 27052239, 'author': 'Will Yu', 'author_id': 1453988, 'author_profile': 'https://Stackoverflow.com/users/1453988', 'pm_score': 4, 'selected': False, 'text': '<p>From a string: (Enum.Parse is out of Date, use Enum.TryParse) </p>\n\n<pre><code>enum Importance\n{}\n\nImportance importance;\n\nif (Enum.TryParse(value, out importance))\n{\n}\n</code></pre>\n'}, {'answer_id': 29343461, 'author': 'Daniel Fisher  lennybacon', 'author_id': 12679, 'author_profile': 'https://Stackoverflow.com/users/12679', 'pm_score': 5, 'selected': False, 'text': '<p>This is an flags enumeration aware safe convert method:</p>\n\n<pre><code>public static bool TryConvertToEnum&lt;T&gt;(this int instance, out T result)\n  where T: Enum\n{\n  var enumType = typeof (T);\n  var success = Enum.IsDefined(enumType, instance);\n  if (success)\n  {\n    result = (T)Enum.ToObject(enumType, instance);\n  }\n  else\n  {\n    result = default(T);\n  }\n  return success;\n}\n</code></pre>\n'}, {'answer_id': 34654243, 'author': 'Franki1986', 'author_id': 1959238, 'author_profile': 'https://Stackoverflow.com/users/1959238', 'pm_score': 3, 'selected': False, 'text': "<p>I don't know anymore where I get the part of this enum extension, but it is from stackoverflow. I am sorry for this! But I took this one and modified it for enums with Flags. \nFor enums with Flags I did this:</p>\n\n<pre><code>  public static class Enum&lt;T&gt; where T : struct\n  {\n     private static readonly IEnumerable&lt;T&gt; All = Enum.GetValues(typeof (T)).Cast&lt;T&gt;();\n     private static readonly Dictionary&lt;int, T&gt; Values = All.ToDictionary(k =&gt; Convert.ToInt32(k));\n\n     public static T? CastOrNull(int value)\n     {\n        T foundValue;\n        if (Values.TryGetValue(value, out foundValue))\n        {\n           return foundValue;\n        }\n\n        // For enums with Flags-Attribut.\n        try\n        {\n           bool isFlag = typeof(T).GetCustomAttributes(typeof(FlagsAttribute), false).Length &gt; 0;\n           if (isFlag)\n           {\n              int existingIntValue = 0;\n\n              foreach (T t in Enum.GetValues(typeof(T)))\n              {\n                 if ((value &amp; Convert.ToInt32(t)) &gt; 0)\n                 {\n                    existingIntValue |= Convert.ToInt32(t);\n                 }\n              }\n              if (existingIntValue == 0)\n              {\n                 return null;\n              }\n\n              return (T)(Enum.Parse(typeof(T), existingIntValue.ToString(), true));\n           }\n        }\n        catch (Exception)\n        {\n           return null;\n        }\n        return null;\n     }\n  }\n</code></pre>\n\n<p>Example:  </p>\n\n<pre><code>[Flags]\npublic enum PetType\n{\n  None = 0, Dog = 1, Cat = 2, Fish = 4, Bird = 8, Reptile = 16, Other = 32\n};\n\ninteger values \n1=Dog;\n13= Dog | Fish | Bird;\n96= Other;\n128= Null;\n</code></pre>\n"}, {'answer_id': 40655361, 'author': 'reza.cse08', 'author_id': 2597706, 'author_profile': 'https://Stackoverflow.com/users/2597706', 'pm_score': 3, 'selected': False, 'text': '<p>It can help you to convert any input data to user desired <strong>enum</strong>. Suppose you have an enum like below which by default <strong>int</strong>. Please add a <strong>Default</strong> value at first of your enum. Which is used at helpers medthod when there is no match found with input value.</p>\n\n<pre><code>public enum FriendType  \n{\n    Default,\n    Audio,\n    Video,\n    Image\n}\n\npublic static class EnumHelper&lt;T&gt;\n{\n    public static T ConvertToEnum(dynamic value)\n    {\n        var result = default(T);\n        var tempType = 0;\n\n        //see Note below\n        if (value != null &amp;&amp;\n            int.TryParse(value.ToString(), out  tempType) &amp;&amp; \n            Enum.IsDefined(typeof(T), tempType))\n        {\n            result = (T)Enum.ToObject(typeof(T), tempType); \n        }\n        return result;\n    }\n}\n</code></pre>\n\n<p><strong>N.B:</strong> Here I try to parse value into int, because enum is by default <strong>int</strong>\nIf you define enum like this which is <strong>byte</strong> type.</p>\n\n<pre><code>public enum MediaType : byte\n{\n    Default,\n    Audio,\n    Video,\n    Image\n} \n</code></pre>\n\n<p>You need to change parsing at helper method from </p>\n\n<pre><code>int.TryParse(value.ToString(), out  tempType)\n</code></pre>\n\n<p>to</p>\n\n<p><code>byte.TryParse(value.ToString(), out  tempType)</code> </p>\n\n<p>I check my method for following inputs</p>\n\n<pre><code>EnumHelper&lt;FriendType&gt;.ConvertToEnum(null);\nEnumHelper&lt;FriendType&gt;.ConvertToEnum("");\nEnumHelper&lt;FriendType&gt;.ConvertToEnum("-1");\nEnumHelper&lt;FriendType&gt;.ConvertToEnum("6");\nEnumHelper&lt;FriendType&gt;.ConvertToEnum("");\nEnumHelper&lt;FriendType&gt;.ConvertToEnum("2");\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(-1);\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(0);\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(1);\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(9);\n</code></pre>\n\n<p>sorry for my english</p>\n'}, {'answer_id': 41178912, 'author': 'Kamran Shahid', 'author_id': 578178, 'author_profile': 'https://Stackoverflow.com/users/578178', 'pm_score': 5, 'selected': False, 'text': '<p>The following is a slightly better extension method:</p>\n<pre><code>public static string ToEnumString&lt;TEnum&gt;(this int enumValue)\n{\n    var enumString = enumValue.ToString();\n    if (Enum.IsDefined(typeof(TEnum), enumValue))\n    {\n        enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();\n    }\n    return enumString;\n}\n</code></pre>\n'}, {'answer_id': 53679705, 'author': 'Mohammad Aziz Nabizada', 'author_id': 10477046, 'author_profile': 'https://Stackoverflow.com/users/10477046', 'pm_score': 4, 'selected': False, 'text': '<p>The easy and clear way for casting an int to enum in C#:</p>\n<pre><code>public class Program\n{\n    public enum Color : int\n    {\n        Blue   = 0,\n        Black  = 1,\n        Green  = 2,\n        Gray   = 3,\n        Yellow = 4\n    }\n\n    public static void Main(string[] args)\n    {\n        // From string\n        Console.WriteLine((Color) Enum.Parse(typeof(Color), &quot;Green&quot;));\n\n        // From int\n        Console.WriteLine((Color)2);\n\n        // From number you can also\n        Console.WriteLine((Color)Enum.ToObject(typeof(Color), 2));\n    }\n}\n</code></pre>\n'}, {'answer_id': 54477333, 'author': 'Shivam Mishra', 'author_id': 6300340, 'author_profile': 'https://Stackoverflow.com/users/6300340', 'pm_score': 3, 'selected': False, 'text': '<p>You simply use <strong>Explicit conversion</strong> Cast int to enum or enum to int</p>\n\n<pre><code>class Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine((int)Number.three); //Output=3\n\n        Console.WriteLine((Number)3);// Outout three\n        Console.Read();\n    }\n\n    public enum Number\n    {\n        Zero = 0,\n        One = 1,\n        Two = 2,\n        three = 3\n    }\n}\n</code></pre>\n'}, {'answer_id': 54818768, 'author': 'Chad Hedgcock', 'author_id': 591097, 'author_profile': 'https://Stackoverflow.com/users/591097', 'pm_score': 4, 'selected': False, 'text': "<p>Here's an extension method that casts <code>Int32</code> to <code>Enum</code>.</p>\n\n<p>It honors bitwise flags even when the value is higher than the maximum possible. For example if you have an enum with possibilities <em>1</em>, <em>2</em>, and <em>4</em>, but the int is <em>9</em>, it understands that as <em>1</em> in absence of an <em>8</em>. This lets you make data updates ahead of code updates.</p>\n\n<pre><code>   public static TEnum ToEnum&lt;TEnum&gt;(this int val) where TEnum : struct, IComparable, IFormattable, IConvertible\n    {\n        if (!typeof(TEnum).IsEnum)\n        {\n            return default(TEnum);\n        }\n\n        if (Enum.IsDefined(typeof(TEnum), val))\n        {//if a straightforward single value, return that\n            return (TEnum)Enum.ToObject(typeof(TEnum), val);\n        }\n\n        var candidates = Enum\n            .GetValues(typeof(TEnum))\n            .Cast&lt;int&gt;()\n            .ToList();\n\n        var isBitwise = candidates\n            .Select((n, i) =&gt; {\n                if (i &lt; 2) return n == 0 || n == 1;\n                return n / 2 == candidates[i - 1];\n            })\n            .All(y =&gt; y);\n\n        var maxPossible = candidates.Sum();\n\n        if (\n            Enum.TryParse(val.ToString(), out TEnum asEnum)\n            &amp;&amp; (val &lt;= maxPossible || !isBitwise)\n        ){//if it can be parsed as a bitwise enum with multiple flags,\n          //or is not bitwise, return the result of TryParse\n            return asEnum;\n        }\n\n        //If the value is higher than all possible combinations,\n        //remove the high imaginary values not accounted for in the enum\n        var excess = Enumerable\n            .Range(0, 32)\n            .Select(n =&gt; (int)Math.Pow(2, n))\n            .Where(n =&gt; n &lt;= val &amp;&amp; n &gt; 0 &amp;&amp; !candidates.Contains(n))\n            .Sum();\n\n        return Enum.TryParse((val - excess).ToString(), out asEnum) ? asEnum : default(TEnum);\n    }\n</code></pre>\n"}, {'answer_id': 56859286, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>You should build in some type matching relaxation to be more robust.</p>\n\n<pre><code>public static T ToEnum&lt;T&gt;(dynamic value)\n{\n    if (value == null)\n    {\n        // default value of an enum is the object that corresponds to\n        // the default value of its underlying type\n        // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table\n        value = Activator.CreateInstance(Enum.GetUnderlyingType(typeof(T)));\n    }\n    else if (value is string name)\n    {\n        return (T)Enum.Parse(typeof(T), name);\n    }\n\n    return (T)Enum.ToObject(typeof(T),\n             Convert.ChangeType(value, Enum.GetUnderlyingType(typeof(T))));\n}\n</code></pre>\n\n<p>Test Case</p>\n\n<pre><code>[Flags]\npublic enum A : uint\n{\n    None  = 0, \n    X     = 1 &lt; 0,\n    Y     = 1 &lt; 1\n}\n\nstatic void Main(string[] args)\n{\n    var value = EnumHelper.ToEnum&lt;A&gt;(7m);\n    var x = value.HasFlag(A.X); // true\n    var y = value.HasFlag(A.Y); // true\n\n    var value2 = EnumHelper.ToEnum&lt;A&gt;("X");\n\n    var value3 = EnumHelper.ToEnum&lt;A&gt;(null);\n\n    Console.ReadKey();\n}\n</code></pre>\n'}, {'answer_id': 57230204, 'author': 'Mselmi Ali', 'author_id': 9091039, 'author_profile': 'https://Stackoverflow.com/users/9091039', 'pm_score': 3, 'selected': False, 'text': '<p>You just do like below:</p>\n\n<pre><code>int intToCast = 1;\nTargetEnum f = (TargetEnum) intToCast ;\n</code></pre>\n\n<p>To make sure that you only cast the right values \u200b\u200band that you can throw an exception otherwise:</p>\n\n<pre><code>int intToCast = 1;\nif (Enum.IsDefined(typeof(TargetEnum), intToCast ))\n{\n    TargetEnum target = (TargetEnum)intToCast ;\n}\nelse\n{\n   // Throw your exception.\n}\n</code></pre>\n\n<p>Note that using IsDefined is costly and even more than just casting, so it depends on your implementation to decide to use it or not.</p>\n'}, {'answer_id': 58427564, 'author': 'Aswal', 'author_id': 3560061, 'author_profile': 'https://Stackoverflow.com/users/3560061', 'pm_score': 3, 'selected': False, 'text': '<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace SamplePrograme\n{\n    public class Program\n    {\n        public enum Suit : int\n        {\n            Spades = 0,\n            Hearts = 1,\n            Clubs = 2,\n            Diamonds = 3\n        }\n\n        public static void Main(string[] args)\n        {\n            //from string\n            Console.WriteLine((Suit) Enum.Parse(typeof(Suit), "Clubs"));\n\n            //from int\n            Console.WriteLine((Suit)1);\n\n            //From number you can also\n            Console.WriteLine((Suit)Enum.ToObject(typeof(Suit) ,1));\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 61416134, 'author': 'Reza Jenabi', 'author_id': 9549856, 'author_profile': 'https://Stackoverflow.com/users/9549856', 'pm_score': 3, 'selected': False, 'text': '<p>You can use an extension method.</p>\n<pre><code>public static class Extensions\n{\n\n    public static T ToEnum&lt;T&gt;(this string data) where T : struct\n    {\n        if (!Enum.TryParse(data, true, out T enumVariable))\n        {\n            if (Enum.IsDefined(typeof(T), enumVariable))\n            {\n                return enumVariable;\n            }\n        }\n\n        return default;\n    }\n\n    public static T ToEnum&lt;T&gt;(this int data) where T : struct\n    {\n        return (T)Enum.ToObject(typeof(T), data);\n    }\n}\n</code></pre>\n<p>Use it like the below code:</p>\n<p><strong>Enum:</strong></p>\n<pre><code>public enum DaysOfWeeks\n{\n    Monday = 1,\n    Tuesday = 2,\n    Wednesday = 3,\n    Thursday = 4,\n    Friday = 5,\n    Saturday = 6,\n    Sunday = 7,\n}\n</code></pre>\n<p><strong>Usage:</strong></p>\n<pre><code> string Monday = &quot;Mon&quot;;\n int Wednesday = 3;\n var Mon = Monday.ToEnum&lt;DaysOfWeeks&gt;();\n var Wed = Wednesday.ToEnum&lt;DaysOfWeeks&gt;();\n</code></pre>\n'}, {'answer_id': 62296386, 'author': 'Inam Abbas', 'author_id': 7258037, 'author_profile': 'https://Stackoverflow.com/users/7258037', 'pm_score': 3, 'selected': False, 'text': '<p>Simple you can cast int to enum</p>\n<pre><code> public enum DaysOfWeeks\n    {\n        Monday = 1,\n        Tuesday = 2,\n        Wednesday = 3,\n        Thursday = 4,\n        Friday = 5,\n        Saturday = 6,\n        Sunday = 7,\n    } \n\n    var day= (DaysOfWeeks)5;\n    Console.WriteLine(&quot;Day is : {0}&quot;, day);\n    Console.ReadLine();\n</code></pre>\n'}, {'answer_id': 62442964, 'author': 'Cesar Alvarado Diaz', 'author_id': 1693210, 'author_profile': 'https://Stackoverflow.com/users/1693210', 'pm_score': 2, 'selected': False, 'text': "<p>I need two instructions:</p>\n<pre><code>YourEnum possibleEnum = (YourEnum)value; // There isn't any guarantee that it is part of the enum\nif (Enum.IsDefined(typeof(YourEnum), possibleEnum))\n{\n    // Value exists in YourEnum\n}\n</code></pre>\n"}, {'answer_id': 64020962, 'author': 'Shah Zain', 'author_id': 5196973, 'author_profile': 'https://Stackoverflow.com/users/5196973', 'pm_score': 4, 'selected': False, 'text': '<p><strong>For string, you can do the following:</strong></p>\n<pre><code>var result = Enum.TryParse(typeof(MyEnum), yourString, out yourEnum) \n</code></pre>\n<p>And make sure to check the result to determine if the conversion failed.</p>\n<p><strong>For int, you can do the following:</strong></p>\n<pre><code>MyEnum someValue = (MyEnum)myIntValue;\n</code></pre>\n'}, {'answer_id': 66050222, 'author': 'Alexander', 'author_id': 208272, 'author_profile': 'https://Stackoverflow.com/users/208272', 'pm_score': 3, 'selected': False, 'text': '<p>I prefer a short way using a nullable enum type variable.</p>\n<pre><code>var enumValue = (MyEnum?)enumInt;\n\nif (!enumValue.HasValue)\n{\n    throw new ArgumentException(nameof(enumValue));\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/29482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/493/']