<p>What's the best way to convert a string to an enumeration value in C#?</p>
<p>I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the corresponding enumeration value.</p>
<p>In an ideal world, I could do something like this:</p>
<pre><code>StatusEnum MyStatus = StatusEnum.Parse(&quot;Active&quot;);
</code></pre>
<p>but that isn't a valid code.</p>

[{'answer_id': 16103, 'author': 'DavidWhitney', 'author_id': 1297, 'author_profile': 'https://Stackoverflow.com/users/1297', 'pm_score': 7, 'selected': False, 'text': '<p>You\'re looking for <a href="https://msdn.microsoft.com/en-us/library/aa328348.aspx" rel="noreferrer">Enum.Parse</a>.</p>\n\n<pre><code>SomeEnum enum = (SomeEnum)Enum.Parse(typeof(SomeEnum), "EnumValue");\n</code></pre>\n'}, {'answer_id': 16104, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 12, 'selected': True, 'text': '<p>In .NET Core and .NET Framework ≥4.0 <a href="https://msdn.microsoft.com/en-us/library/dd783499%28v=vs.110%29.aspx" rel="noreferrer">there is a generic parse method</a>:</p>\n<pre><code>Enum.TryParse(&quot;Active&quot;, out StatusEnum myStatus);\n</code></pre>\n<p>This also includes C#7\'s new inline <code>out</code> variables, so this does the try-parse, conversion to the explicit enum type and initialises+populates the <code>myStatus</code> variable.</p>\n<p>If you have access to C#7 and the latest .NET this is the best way.</p>\n<h2>Original Answer</h2>\n<p>In .NET it\'s rather ugly (until 4 or above):</p>\n<pre><code>StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), &quot;Active&quot;, true);\n</code></pre>\n<p>I tend to simplify this with:</p>\n<pre><code>public static T ParseEnum&lt;T&gt;(string value)\n{\n    return (T) Enum.Parse(typeof(T), value, true);\n}\n</code></pre>\n<p>Then I can do:</p>\n<pre><code>StatusEnum MyStatus = EnumUtil.ParseEnum&lt;StatusEnum&gt;(&quot;Active&quot;);\n</code></pre>\n<p>One option suggested in the comments is to add an extension, which is simple enough:</p>\n<pre><code>public static T ToEnum&lt;T&gt;(this string value)\n{\n    return (T) Enum.Parse(typeof(T), value, true);\n}\n\nStatusEnum MyStatus = &quot;Active&quot;.ToEnum&lt;StatusEnum&gt;();\n</code></pre>\n<p>Finally, you may want to have a default enum to use if the string cannot be parsed:</p>\n<pre><code>public static T ToEnum&lt;T&gt;(this string value, T defaultValue) \n{\n    if (string.IsNullOrEmpty(value))\n    {\n        return defaultValue;\n    }\n\n    T result;\n    return Enum.TryParse&lt;T&gt;(value, true, out result) ? result : defaultValue;\n}\n</code></pre>\n<p>Which makes this the call:</p>\n<pre><code>StatusEnum MyStatus = &quot;Active&quot;.ToEnum(StatusEnum.None);\n</code></pre>\n<p>However, I would be careful adding an extension method like this to <code>string</code> as (without namespace control) it will appear on all instances of <code>string</code> whether they hold an enum or not (so <code>1234.ToString().ToEnum(StatusEnum.None)</code> would be valid but nonsensical) . It\'s often be best to avoid cluttering Microsoft\'s core classes with extra methods that only apply in very specific contexts unless your entire development team has a very good understanding of what those extensions do.</p>\n'}, {'answer_id': 16107, 'author': 'tags2k', 'author_id': 192, 'author_profile': 'https://Stackoverflow.com/users/192', 'pm_score': 4, 'selected': False, 'text': '<p><a href="https://msdn.microsoft.com/en-us/library/aa328348.aspx" rel="noreferrer">Enum.Parse</a> is your friend:</p>\n\n<pre><code>StatusEnum MyStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), "Active");\n</code></pre>\n'}, {'answer_id': 16112, 'author': 'brendan', 'author_id': 225, 'author_profile': 'https://Stackoverflow.com/users/225', 'pm_score': 5, 'selected': False, 'text': '<pre><code>object Enum.Parse(System.Type enumType, string value, bool ignoreCase);\n</code></pre>\n\n<p>So if you had an enum named mood it would look like this:</p>\n\n<pre><code>   enum Mood\n   {\n      Angry,\n      Happy,\n      Sad\n   } \n\n   // ...\n   Mood m = (Mood) Enum.Parse(typeof(Mood), "Happy", true);\n   Console.WriteLine("My mood is: {0}", m.ToString());</code></pre>\n'}, {'answer_id': 16131, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 3, 'selected': False, 'text': '<pre><code>// str.ToEnum&lt;EnumType&gt;()\nT static ToEnum&lt;T&gt;(this string str) \n{ \n    return (T) Enum.Parse(typeof(T), str);\n}\n</code></pre>\n'}, {'answer_id': 38711, 'author': 'McKenzieG1', 'author_id': 3776, 'author_profile': 'https://Stackoverflow.com/users/3776', 'pm_score': 8, 'selected': False, 'text': '<p>Note that the performance of <code>Enum.Parse()</code> is not ideal, because it is implemented via reflection. (The same is true of <code>Enum.ToString()</code>, which goes the other way.)</p>\n<p>If you need to convert strings to Enums in performance-sensitive code, your best bet is to create a <code>Dictionary&lt;String,YourEnum&gt;</code> at startup and use that to do your conversions.</p>\n'}, {'answer_id': 12199994, 'author': 'gap', 'author_id': 438205, 'author_profile': 'https://Stackoverflow.com/users/438205', 'pm_score': 4, 'selected': False, 'text': "<p>We couldn't assume perfectly valid input, and went with this variation of @Keith's answer:</p>\n\n<pre><code>public static TEnum ParseEnum&lt;TEnum&gt;(string value) where TEnum : struct\n{\n    TEnum tmp; \n    if (!Enum.TryParse&lt;TEnum&gt;(value, true, out tmp))\n    {\n        tmp = new TEnum();\n    }\n    return tmp;\n}\n</code></pre>\n"}, {'answer_id': 19431735, 'author': 'jite.gs', 'author_id': 2891293, 'author_profile': 'https://Stackoverflow.com/users/2891293', 'pm_score': 3, 'selected': False, 'text': '<p>Parses string to TEnum without try/catch and without TryParse() method from .NET 4.5</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Parses string to TEnum without try/catch and .NET 4.5 TryParse()\n/// &lt;/summary&gt;\npublic static bool TryParseToEnum&lt;TEnum&gt;(string probablyEnumAsString_, out TEnum enumValue_) where TEnum : struct\n{\n    enumValue_ = (TEnum)Enum.GetValues(typeof(TEnum)).GetValue(0);\n    if(!Enum.IsDefined(typeof(TEnum), probablyEnumAsString_))\n        return false;\n\n    enumValue_ = (TEnum) Enum.Parse(typeof(TEnum), probablyEnumAsString_);\n    return true;\n}\n</code></pre>\n'}, {'answer_id': 20394856, 'author': 'Erwin Mayer', 'author_id': 541420, 'author_profile': 'https://Stackoverflow.com/users/541420', 'pm_score': 9, 'selected': False, 'text': '<p>Use <a href="http://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&amp;l=EN-US&amp;k=k%28System.Enum.TryParse%60%601%29;k%28SolutionItemsProject%29;k%28TargetFrameworkMoniker-.NETFramework,Version=v4.5%29;k%28DevLang-csharp%29&amp;rd=true" rel="noreferrer"><code>Enum.TryParse&lt;T&gt;(String, T)</code></a> (≥ .NET 4.0):</p>\n\n<pre><code>StatusEnum myStatus;\nEnum.TryParse("Active", out myStatus);\n</code></pre>\n\n<p>It can be simplified even further with C# 7.0\'s <a href="https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/" rel="noreferrer">parameter type inlining</a>:</p>\n\n<pre><code>Enum.TryParse("Active", out StatusEnum myStatus);\n</code></pre>\n'}, {'answer_id': 21674259, 'author': 'Foyzul Karim', 'author_id': 326597, 'author_profile': 'https://Stackoverflow.com/users/326597', 'pm_score': 5, 'selected': False, 'text': '<p>You can use <a href="https://en.wikipedia.org/wiki/Extension_method#Extension_methods">extension methods</a> now:</p>\n\n<pre><code>public static T ToEnum&lt;T&gt;(this string value, bool ignoreCase = true)\n{\n    return (T) Enum.Parse(typeof (T), value, ignoreCase);\n}\n</code></pre>\n\n<p>And you can call them by the below code (here, <code>FilterType</code> is an enum type):</p>\n\n<pre><code>FilterType filterType = type.ToEnum&lt;FilterType&gt;();\n</code></pre>\n'}, {'answer_id': 27378161, 'author': 'Nelly', 'author_id': 3181564, 'author_profile': 'https://Stackoverflow.com/users/3181564', 'pm_score': 4, 'selected': False, 'text': '<p>You can extend the accepted answer with a default value to avoid exceptions:</p>\n\n<pre><code>public static T ParseEnum&lt;T&gt;(string value, T defaultValue) where T : struct\n{\n    try\n    {\n        T enumValue;\n        if (!Enum.TryParse(value, true, out enumValue))\n        {\n            return defaultValue;\n        }\n        return enumValue;\n    }\n    catch (Exception)\n    {\n        return defaultValue;\n    }\n}\n</code></pre>\n\n<p>Then you call it like:</p>\n\n<pre><code>StatusEnum MyStatus = EnumUtil.ParseEnum("Active", StatusEnum.None);\n</code></pre>\n\n<p>If the default value is not an enum the Enum.TryParse would fail and throw an exception which is catched.</p>\n\n<p>After years of using this function in our code on many places maybe it\'s good to add the information that this operation costs performance!</p>\n'}, {'answer_id': 31157772, 'author': 'Patrik Lindström', 'author_id': 648076, 'author_profile': 'https://Stackoverflow.com/users/648076', 'pm_score': 2, 'selected': False, 'text': '<p>I used class (strongly-typed version of Enum with parsing and performance improvements). I found it on GitHub, and it should work for .NET 3.5 too. It has some memory overhead since it buffers a dictionary.</p>\n\n<pre><code>StatusEnum MyStatus = Enum&lt;StatusEnum&gt;.Parse("Active");\n</code></pre>\n\n<p>The blogpost is <em><a href="http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5" rel="nofollow">Enums – Better syntax, improved performance and TryParse in NET 3.5</a></em>.</p>\n\n<p>And code:\n<a href="https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/System/EnumT.cs" rel="nofollow">https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/System/EnumT.cs</a></p>\n'}, {'answer_id': 32064171, 'author': 'Rae Lee', 'author_id': 5113582, 'author_profile': 'https://Stackoverflow.com/users/5113582', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public static T ParseEnum&lt;T&gt;(string value)            //function declaration  \n{\n    return (T) Enum.Parse(typeof(T), value);\n}\n\nImportance imp = EnumUtil.ParseEnum&lt;Importance&gt;("Active");   //function call\n</code></pre>\n\n<p>====================A Complete Program====================</p>\n\n<pre><code>using System;\n\nclass Program\n{\n    enum PetType\n    {\n    None,\n    Cat = 1,\n    Dog = 2\n    }\n\n    static void Main()\n    {\n\n    // Possible user input:\n    string value = "Dog";\n\n    // Try to convert the string to an enum:\n    PetType pet = (PetType)Enum.Parse(typeof(PetType), value);\n\n    // See if the conversion succeeded:\n    if (pet == PetType.Dog)\n    {\n        Console.WriteLine("Equals dog.");\n    }\n    }\n}\n-------------\nOutput\n\nEquals dog.\n</code></pre>\n'}, {'answer_id': 32897493, 'author': 'alhpe', 'author_id': 2998185, 'author_profile': 'https://Stackoverflow.com/users/2998185', 'pm_score': 3, 'selected': False, 'text': '<p>I like the extension method solution..</p>\n\n<pre><code>namespace System\n{\n    public static class StringExtensions\n    {\n\n        public static bool TryParseAsEnum&lt;T&gt;(this string value, out T output) where T : struct\n        {\n            T result;\n\n            var isEnum = Enum.TryParse(value, out result);\n\n            output = isEnum ? result : default(T);\n\n            return isEnum;\n        }\n    }\n}\n</code></pre>\n\n<p>Here below my implementation with tests.</p>\n\n<pre><code>using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert;\nusing static System.Console;\n\nprivate enum Countries\n    {\n        NorthAmerica,\n        Europe,\n        Rusia,\n        Brasil,\n        China,\n        Asia,\n        Australia\n    }\n\n   [TestMethod]\n        public void StringExtensions_On_TryParseAsEnum()\n        {\n            var countryName = "Rusia";\n\n            Countries country;\n            var isCountry = countryName.TryParseAsEnum(out country);\n\n            WriteLine(country);\n\n            IsTrue(isCountry);\n            AreEqual(Countries.Rusia, country);\n\n            countryName = "Don\'t exist";\n\n            isCountry = countryName.TryParseAsEnum(out country);\n\n            WriteLine(country);\n\n            IsFalse(isCountry);\n            AreEqual(Countries.NorthAmerica, country); // the 1rst one in the enumeration\n        }\n</code></pre>\n'}, {'answer_id': 34267134, 'author': 'Timo', 'author_id': 543814, 'author_profile': 'https://Stackoverflow.com/users/543814', 'pm_score': 5, 'selected': False, 'text': '<p><strong>BEWARE:</strong></p>\n\n<pre><code>enum Example\n{\n    One = 1,\n    Two = 2,\n    Three = 3\n}\n</code></pre>\n\n<p><code>Enum.(Try)Parse()</code> <strong>accepts multiple, comma-separated arguments, and combines them with binary \'or\' <code>|</code></strong>. You cannot disable this and in my opinion you almost never want it.</p>\n\n<pre><code>var x = Enum.Parse("One,Two"); // x is now Three\n</code></pre>\n\n<p>Even if <code>Three</code> was not defined, <code>x</code> would still get int value <code>3</code>. That\'s even worse: Enum.Parse() can give you a value that is not even defined for the enum!</p>\n\n<p>I would not want to experience the consequences of users, willingly or unwillingly, triggering this behavior.</p>\n\n<p>Additionally, as mentioned by others, performance is less than ideal for large enums, namely linear in the number of possible values.</p>\n\n<p>I suggest the following:</p>\n\n<pre><code>    public static bool TryParse&lt;T&gt;(string value, out T result)\n        where T : struct\n    {\n        var cacheKey = "Enum_" + typeof(T).FullName;\n\n        // [Use MemoryCache to retrieve or create&amp;store a dictionary for this enum, permanently or temporarily.\n        // [Implementation off-topic.]\n        var enumDictionary = CacheHelper.GetCacheItem(cacheKey, CreateEnumDictionary&lt;T&gt;, EnumCacheExpiration);\n\n        return enumDictionary.TryGetValue(value.Trim(), out result);\n    }\n\n    private static Dictionary&lt;string, T&gt; CreateEnumDictionary&lt;T&gt;()\n    {\n        return Enum.GetValues(typeof(T))\n            .Cast&lt;T&gt;()\n            .ToDictionary(value =&gt; value.ToString(), value =&gt; value, StringComparer.OrdinalIgnoreCase);\n    }\n</code></pre>\n'}, {'answer_id': 37970592, 'author': 'Koray', 'author_id': 1266873, 'author_profile': 'https://Stackoverflow.com/users/1266873', 'pm_score': 2, 'selected': False, 'text': '<p>For performance this might help:</p>\n\n<pre><code>    private static Dictionary&lt;Type, Dictionary&lt;string, object&gt;&gt; dicEnum = new Dictionary&lt;Type, Dictionary&lt;string, object&gt;&gt;();\n    public static T ToEnum&lt;T&gt;(this string value, T defaultValue)\n    {\n        var t = typeof(T);\n        Dictionary&lt;string, object&gt; dic;\n        if (!dicEnum.ContainsKey(t))\n        {\n            dic = new Dictionary&lt;string, object&gt;();\n            dicEnum.Add(t, dic);\n            foreach (var en in Enum.GetValues(t))\n                dic.Add(en.ToString(), en);\n        }\n        else\n            dic = dicEnum[t];\n        if (!dic.ContainsKey(value))\n            return defaultValue;\n        else\n            return (T)dic[value];\n    }\n</code></pre>\n'}, {'answer_id': 39857622, 'author': 'isxaker', 'author_id': 364429, 'author_profile': 'https://Stackoverflow.com/users/364429', 'pm_score': 2, 'selected': False, 'text': '<p>I found that here the case with enum values that have EnumMember value was not considered. So here we go:</p>\n\n<pre><code>using System.Runtime.Serialization;\n\npublic static TEnum ToEnum&lt;TEnum&gt;(this string value, TEnum defaultValue) where TEnum : struct\n{\n    if (string.IsNullOrEmpty(value))\n    {\n        return defaultValue;\n    }\n\n    TEnum result;\n    var enumType = typeof(TEnum);\n    foreach (var enumName in Enum.GetNames(enumType))\n    {\n        var fieldInfo = enumType.GetField(enumName);\n        var enumMemberAttribute = ((EnumMemberAttribute[]) fieldInfo.GetCustomAttributes(typeof(EnumMemberAttribute), true)).FirstOrDefault();\n        if (enumMemberAttribute?.Value == value)\n        {\n            return Enum.TryParse(enumName, true, out result) ? result : defaultValue;\n        }\n    }\n\n    return Enum.TryParse(value, true, out result) ? result : defaultValue;\n}\n</code></pre>\n\n<p>And example of that enum:</p>\n\n<pre><code>public enum OracleInstanceStatus\n{\n    Unknown = -1,\n    Started = 1,\n    Mounted = 2,\n    Open = 3,\n    [EnumMember(Value = "OPEN MIGRATE")]\n    OpenMigrate = 4\n}\n</code></pre>\n'}, {'answer_id': 40796886, 'author': 'Brian Rice', 'author_id': 1027031, 'author_profile': 'https://Stackoverflow.com/users/1027031', 'pm_score': 3, 'selected': False, 'text': '<p>Super simple code using TryParse:</p>\n\n<pre><code>var value = "Active";\n\nStatusEnum status;\nif (!Enum.TryParse&lt;StatusEnum&gt;(value, out status))\n    status = StatusEnum.Unknown;\n</code></pre>\n'}, {'answer_id': 42111987, 'author': 'Bartosz Gawron', 'author_id': 6888393, 'author_profile': 'https://Stackoverflow.com/users/6888393', 'pm_score': 2, 'selected': False, 'text': '<p>You have to use Enum.Parse to get the object value from Enum, after that you have to change the object value to specific enum value. Casting to enum value can be do by using Convert.ChangeType. Please have a look on following code snippet</p>\n\n<pre><code>public T ConvertStringValueToEnum&lt;T&gt;(string valueToParse){\n    return Convert.ChangeType(Enum.Parse(typeof(T), valueToParse, true), typeof(T));\n}\n</code></pre>\n'}, {'answer_id': 52588251, 'author': 'AmirReza-Farahlagha', 'author_id': 7059557, 'author_profile': 'https://Stackoverflow.com/users/7059557', 'pm_score': 2, 'selected': False, 'text': '<p>Try this sample:</p>\n\n<pre><code> public static T GetEnum&lt;T&gt;(string model)\n    {\n        var newModel = GetStringForEnum(model);\n\n        if (!Enum.IsDefined(typeof(T), newModel))\n        {\n            return (T)Enum.Parse(typeof(T), "None", true);\n        }\n\n        return (T)Enum.Parse(typeof(T), newModel.Result, true);\n    }\n\n    private static Task&lt;string&gt; GetStringForEnum(string model)\n    {\n        return Task.Run(() =&gt;\n        {\n            Regex rgx = new Regex("[^a-zA-Z0-9 -]");\n            var nonAlphanumericData = rgx.Matches(model);\n            if (nonAlphanumericData.Count &lt; 1)\n            {\n                return model;\n            }\n            foreach (var item in nonAlphanumericData)\n            {\n                model = model.Replace((string)item, "");\n            }\n            return model;\n        });\n    }\n</code></pre>\n\n<p>In this sample you can send every string, and set your <code>Enum</code>. If your <code>Enum</code> had data that you wanted, return that as your <code>Enum</code> type.</p>\n'}, {'answer_id': 56251256, 'author': 'AHMED RABEE', 'author_id': 1294770, 'author_profile': 'https://Stackoverflow.com/users/1294770', 'pm_score': 1, 'selected': False, 'text': '<pre><code>        &lt;Extension()&gt;\n    Public Function ToEnum(Of TEnum)(ByVal value As String, ByVal defaultValue As TEnum) As TEnum\n        If String.IsNullOrEmpty(value) Then\n            Return defaultValue\n        End If\n\n        Return [Enum].Parse(GetType(TEnum), value, True)\n    End Function\n</code></pre>\n'}, {'answer_id': 56251321, 'author': 'AHMED RABEE', 'author_id': 1294770, 'author_profile': 'https://Stackoverflow.com/users/1294770', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public TEnum ToEnum&lt;TEnum&gt;(this string value, TEnum defaultValue){\nif (string.IsNullOrEmpty(value))\n    return defaultValue;\n\nreturn Enum.Parse(typeof(TEnum), value, true);}\n</code></pre>\n'}, {'answer_id': 59076571, 'author': 'JCisar', 'author_id': 1179562, 'author_profile': 'https://Stackoverflow.com/users/1179562', 'pm_score': 3, 'selected': False, 'text': '<p>Not sure when this was added but on the Enum class there is now a </p>\n\n<p><code>Parse&lt;TEnum&gt;(stringValue)</code></p>\n\n<p>Used like so with example in question:</p>\n\n<p><code>var MyStatus = Enum.Parse&lt;StatusEnum &gt;("Active")</code></p>\n\n<p>or ignoring casing by:</p>\n\n<p><code>var MyStatus = Enum.Parse&lt;StatusEnum &gt;("active", true)</code></p>\n\n<p>Here is the decompiled methods this uses:</p>\n\n<pre class="lang-cs prettyprint-override"><code>    [NullableContext(0)]\n    public static TEnum Parse&lt;TEnum&gt;([Nullable(1)] string value) where TEnum : struct\n    {\n      return Enum.Parse&lt;TEnum&gt;(value, false);\n    }\n\n    [NullableContext(0)]\n    public static TEnum Parse&lt;TEnum&gt;([Nullable(1)] string value, bool ignoreCase) where TEnum : struct\n    {\n      TEnum result;\n      Enum.TryParse&lt;TEnum&gt;(value, ignoreCase, true, out result);\n      return result;\n    }\n</code></pre>\n'}, {'answer_id': 59897419, 'author': 'Joel Wiklund', 'author_id': 583037, 'author_profile': 'https://Stackoverflow.com/users/583037', 'pm_score': 2, 'selected': False, 'text': '<p>If the property name is different from what you want to call it (i.e. language differences) you can do like this:</p>\n\n<p>MyType.cs</p>\n\n<pre><code>using System;\nusing System.Runtime.Serialization;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Converters;\n\n[JsonConverter(typeof(StringEnumConverter))]\npublic enum MyType\n{\n    [EnumMember(Value = "person")]\n    Person,\n    [EnumMember(Value = "annan_deltagare")]\n    OtherPerson,\n    [EnumMember(Value = "regel")]\n    Rule,\n}\n</code></pre>\n\n<p>EnumExtensions.cs</p>\n\n<pre><code>using System;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Converters;\n\npublic static class EnumExtensions\n{\n    public static TEnum ToEnum&lt;TEnum&gt;(this string value) where TEnum : Enum\n    {\n        var jsonString = $"\'{value.ToLower()}\'";\n        return JsonConvert.DeserializeObject&lt;TEnum&gt;(jsonString, new StringEnumConverter());\n    }\n\n    public static bool EqualsTo&lt;TEnum&gt;(this string strA, TEnum enumB) where TEnum : Enum\n    {\n        TEnum enumA;\n        try\n        {\n            enumA = strA.ToEnum&lt;TEnum&gt;();\n        }\n        catch\n        {\n            return false;\n        }\n        return enumA.Equals(enumB);\n    }\n}\n</code></pre>\n\n<p>Program.cs</p>\n\n<pre><code>public class Program\n{\n    static public void Main(String[] args) \n    { \n        var myString = "annan_deltagare";\n        var myType = myString.ToEnum&lt;MyType&gt;();\n        var isEqual = myString.EqualsTo(MyType.OtherPerson);\n        //Output: true\n    }     \n}\n</code></pre>\n'}, {'answer_id': 62345657, 'author': 'MBWise', 'author_id': 2454604, 'author_profile': 'https://Stackoverflow.com/users/2454604', 'pm_score': 1, 'selected': False, 'text': '<p>If you want to use a default value when null or empty (e.g. when retrieving from config file and the value does not exist) and throw an exception when the string or number does not match any of the enum values. Beware of caveat in Timo\'s answer though (<a href="https://stackoverflow.com/a/34267134/2454604">https://stackoverflow.com/a/34267134/2454604</a>).</p>\n\n<pre><code>    public static T ParseEnum&lt;T&gt;(this string s, T defaultValue, bool ignoreCase = false) \n        where T : struct, IComparable, IConvertible, IFormattable//If C# &gt;=7.3: struct, System.Enum \n    {\n        if ((s?.Length ?? 0) == 0)\n        {\n            return defaultValue;\n        }\n\n        var valid = Enum.TryParse&lt;T&gt;(s, ignoreCase, out T res);\n\n        if (!valid || !Enum.IsDefined(typeof(T), res))\n        {\n            throw new InvalidOperationException(\n                $"\'{s}\' is not a valid value of enum \'{typeof(T).FullName}\'!");\n        }\n        return res;\n    }\n</code></pre>\n'}, {'answer_id': 66977781, 'author': 'Felipe Augusto', 'author_id': 8104755, 'author_profile': 'https://Stackoverflow.com/users/8104755', 'pm_score': -1, 'selected': False, 'text': '<p>First of all, you need to decorate your enum, like this:</p>\n<pre><code>    public enum Store : short\n{\n    [Description(&quot;Rio Big Store&quot;)]\n    Rio = 1\n}\n</code></pre>\n<p>in .net 5, i create this extension method:</p>\n<pre><code>//The class also needs to be static, ok?\npublic static string GetDescription(this System.Enum enumValue)\n    {\n        FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());\n\n        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(\n            typeof(DescriptionAttribute), false);\n\n        if (attributes != null &amp;&amp; attributes.Length &gt; 0) return attributes[0].Description;\n        else return enumValue.ToString();\n    }\n</code></pre>\n<p>now you have an extension methods to use in any Enums</p>\n<p>Like this:</p>\n<pre><code>var Desc = Store.Rio.GetDescription(); //Store is your Enum\n</code></pre>\n'}, {'answer_id': 69637069, 'author': 'Jordan Ryder', 'author_id': 2088676, 'author_profile': 'https://Stackoverflow.com/users/2088676', 'pm_score': 4, 'selected': False, 'text': '<p>At some point a generic version of Parse was added. For me this was preferable because I didn\'t need to &quot;try&quot; to parse and I also want the result inline without generating an output variable.</p>\n<pre><code>ColorEnum color = Enum.Parse&lt;ColorEnum&gt;(&quot;blue&quot;);\n</code></pre>\n<p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-5.0#System_Enum_Parse__1_System_String_" rel="noreferrer">MS Documentation: Parse</a></p>\n'}, {'answer_id': 71249113, 'author': 'Bloggrammer', 'author_id': 12476466, 'author_profile': 'https://Stackoverflow.com/users/12476466', 'pm_score': 3, 'selected': False, 'text': "<p>Most of the answers here require you to always pass in the default value of the enum each time you call on the extension method. If you don't want to go by that approach, you can implement it like below:</p>\n<pre><code> public static TEnum ToEnum&lt;TEnum&gt;(this string value) where TEnum : struct\n {\n     if (string.IsNullOrWhiteSpace(value))\n          return default(TEnum);\n\n     return Enum.TryParse(value, true, out TEnum result) ? result : default(TEnum);\n\n }\n</code></pre>\n<p><strong>Using default literal (available from C# 7.1)</strong></p>\n<pre><code> public static TEnum ToEnum&lt;TEnum&gt;(this string value, TEnum defaultValue = default) where TEnum : struct\n {\n       if (string.IsNullOrWhiteSpace(value))\n            return defaultValue ;\n\n       return Enum.TryParse(value, true, out TEnum result) ? result : defaultValue ;\n\n }\n</code></pre>\n<p><strong>Better still:</strong></p>\n<pre><code>public static TEnum ToEnum&lt;TEnum&gt;(this string value) where TEnum : struct\n{\n      if (string.IsNullOrWhiteSpace(value))\n           return default;\n\n      return Enum.TryParse(value, true, out TEnum result) ? result : default;\n\n}\n</code></pre>\n"}, {'answer_id': 72832417, 'author': 'shvets', 'author_id': 7432218, 'author_profile': 'https://Stackoverflow.com/users/7432218', 'pm_score': 0, 'selected': False, 'text': '<p>I started to use this approach. Performance seems to be ok however it requires a bit of boilerplate code setup.</p>\n<pre><code>public enum StatusType {\n    Success,\n    Pending,\n    Rejected\n}\n\nstatic class StatusTypeMethods {\n\n    public static StatusType GetEnum(string type) {\n        switch (type) {\n            case nameof(StatusType.Success): return StatusType.Success;\n            case nameof(StatusType.Pending): return StatusType.Pending;\n            case nameof(StatusType.Rejected): return StatusType.Rejected;\n            default:\n                throw new ArgumentOutOfRangeException(nameof(type), type, null);\n        };\n    }\n}\n</code></pre>\n<p>And later on, you can use it like this:</p>\n<pre><code>StatusType = StatusType.GetEnum(&quot;Success&quot;);\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/16100', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/203/']