<p>I'm building a function to extend the <code>Enum.Parse</code> concept that</p>
<ul>
<li>Allows a default value to be parsed in case that an Enum value is not found</li>
<li>Is case insensitive</li>
</ul>
<p>So I wrote the following:</p>
<pre><code>public static T GetEnumFromString&lt;T&gt;(string value, T defaultValue) where T : Enum
{
    if (string.IsNullOrEmpty(value)) return defaultValue;
    foreach (T item in Enum.GetValues(typeof(T)))
    {
        if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
    }
    return defaultValue;
}
</code></pre>
<p>I am getting a Error Constraint cannot be special class <code>System.Enum</code>.</p>
<p>Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the <code>Parse</code> function and pass a type as an attribute, which forces the ugly boxing requirement to your code.</p>
<p><strong>EDIT</strong> All suggestions below have been greatly appreciated, thanks.</p>
<p>Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML)</p>
<pre><code>public static class EnumUtils
{
    public static T ParseEnum&lt;T&gt;(string value, T defaultValue) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum) throw new ArgumentException(&quot;T must be an enumerated type&quot;);
        if (string.IsNullOrEmpty(value)) return defaultValue;

        foreach (T item in Enum.GetValues(typeof(T)))
        {
            if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
        }
        return defaultValue;
    }
}
</code></pre>
<p><strong>EDIT:</strong> (16th Feb 2015) Christopher Currens has posted <a href="https://stackoverflow.com/a/8086788">a compiler enforced type-safe generic solution in MSIL or F#</a> below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page.</p>
<p><strong>EDIT 2:</strong> (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)</p>

[{'answer_id': 79148, 'author': 'dimarzionist', 'author_id': 10778, 'author_profile': 'https://Stackoverflow.com/users/10778', 'pm_score': 3, 'selected': False, 'text': '<p>Hope this is helpful:</p>\n\n<pre><code>public static TValue ParseEnum&lt;TValue&gt;(string value, TValue defaultValue)\n                  where TValue : struct // enum \n{\n      try\n      {\n            if (String.IsNullOrEmpty(value))\n                  return defaultValue;\n            return (TValue)Enum.Parse(typeof (TValue), value);\n      }\n      catch(Exception ex)\n      {\n            return defaultValue;\n      }\n}\n</code></pre>\n'}, {'answer_id': 79251, 'author': 'Bivoauc', 'author_id': 14715, 'author_profile': 'https://Stackoverflow.com/users/14715', 'pm_score': 4, 'selected': False, 'text': '<p>I modified the sample by dimarzionist. This version will only work with Enums and not let structs get through. </p>\n\n<pre><code>public static T ParseEnum&lt;T&gt;(string enumString)\n    where T : struct // enum \n    {\n    if (String.IsNullOrEmpty(enumString) || !typeof(T).IsEnum)\n       throw new Exception("Type given must be an Enum");\n    try\n    {\n\n       return (T)Enum.Parse(typeof(T), enumString, true);\n    }\n    catch (Exception ex)\n    {\n       return default(T);\n    }\n}\n</code></pre>\n'}, {'answer_id': 79319, 'author': 'Karg', 'author_id': 12685, 'author_profile': 'https://Stackoverflow.com/users/12685', 'pm_score': 4, 'selected': False, 'text': '<p>You can define a static constructor for the class that will check that the type T is an enum and throw an exception if it is not. This is the method mentioned by Jeffery Richter in his book CLR via C#.</p>\n\n<pre><code>internal sealed class GenericTypeThatRequiresAnEnum&lt;T&gt; {\n    static GenericTypeThatRequiresAnEnum() {\n        if (!typeof(T).IsEnum) {\n        throw new ArgumentException("T must be an enumerated type");\n        }\n    }\n}\n</code></pre>\n\n<p>Then in the parse method, you can just use Enum.Parse(typeof(T), input, true) to convert from string to the enum. The last true parameter is for ignoring case of the input. </p>\n'}, {'answer_id': 79903, 'author': 'Vivek', 'author_id': 7418, 'author_profile': 'https://Stackoverflow.com/users/7418', 'pm_score': 10, 'selected': False, 'text': '<p>Since <code>Enum</code> Type implements <code>IConvertible</code> interface, a better implementation should be something like this:</p>\n\n<pre><code>public T GetEnumFromString&lt;T&gt;(string value) where T : struct, IConvertible\n{\n   if (!typeof(T).IsEnum) \n   {\n      throw new ArgumentException("T must be an enumerated type");\n   }\n\n   //...\n}\n</code></pre>\n\n<p>This will still permit passing of value types implementing <code>IConvertible</code>. The chances are rare though.</p>\n'}, {'answer_id': 1093531, 'author': 'Andrew', 'author_id': 15127, 'author_profile': 'https://Stackoverflow.com/users/15127', 'pm_score': 2, 'selected': False, 'text': '<p>Interestingly enough, apparently this is <a href="http://social.msdn.microsoft.com/Forums/en-US/vs2010ctpvbcs/thread/5844d719-3ef6-4000-913c-27c108269e71" rel="nofollow noreferrer">possible in other langauges</a> (Managed C++, IL directly).  </p>\n\n<p>To Quote:</p>\n\n<blockquote>\n  <p>... Both constraints actually produce valid IL and can also be consumed by C# if written in another language (you can declare those constraints in managed C++ or in IL).</p>\n</blockquote>\n\n<p>Who knows </p>\n'}, {'answer_id': 2661254, 'author': 'Sunny Rajwadi', 'author_id': 319544, 'author_profile': 'https://Stackoverflow.com/users/319544', 'pm_score': 3, 'selected': False, 'text': '<p>I do have specific requirement where I required to use enum with text associated with enum value. For example when I use enum to specify error type it required to describe error details.</p>\n\n<pre><code>public static class XmlEnumExtension\n{\n    public static string ReadXmlEnumAttribute(this Enum value)\n    {\n        if (value == null) throw new ArgumentNullException("value");\n        var attribs = (XmlEnumAttribute[]) value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (XmlEnumAttribute), true);\n        return attribs.Length &gt; 0 ? attribs[0].Name : value.ToString();\n    }\n\n    public static T ParseXmlEnumAttribute&lt;T&gt;(this string str)\n    {\n        foreach (T item in Enum.GetValues(typeof(T)))\n        {\n            var attribs = (XmlEnumAttribute[])item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(XmlEnumAttribute), true);\n            if(attribs.Length &gt; 0 &amp;&amp; attribs[0].Name.Equals(str)) return item;\n        }\n        return (T)Enum.Parse(typeof(T), str, true);\n    }\n}\n\npublic enum MyEnum\n{\n    [XmlEnum("First Value")]\n    One,\n    [XmlEnum("Second Value")]\n    Two,\n    Three\n}\n\n static void Main()\n {\n    // Parsing from XmlEnum attribute\n    var str = "Second Value";\n    var me = str.ParseXmlEnumAttribute&lt;MyEnum&gt;();\n    System.Console.WriteLine(me.ReadXmlEnumAttribute());\n    // Parsing without XmlEnum\n    str = "Three";\n    me = str.ParseXmlEnumAttribute&lt;MyEnum&gt;();\n    System.Console.WriteLine(me.ReadXmlEnumAttribute());\n    me = MyEnum.One;\n    System.Console.WriteLine(me.ReadXmlEnumAttribute());\n}\n</code></pre>\n'}, {'answer_id': 3859812, 'author': 'Jeff', 'author_id': 164438, 'author_profile': 'https://Stackoverflow.com/users/164438', 'pm_score': 2, 'selected': False, 'text': '<p>I always liked this (you could modify as appropriate):</p>\n\n<pre><code>public static IEnumerable&lt;TEnum&gt; GetEnumValues()\n{\n  Type enumType = typeof(TEnum);\n\n  if(!enumType.IsEnum)\n    throw new ArgumentException("Type argument must be Enum type");\n\n  Array enumValues = Enum.GetValues(enumType);\n  return enumValues.Cast&lt;TEnum&gt;();\n}\n</code></pre>\n'}, {'answer_id': 4460247, 'author': 'Martin', 'author_id': 394076, 'author_profile': 'https://Stackoverflow.com/users/394076', 'pm_score': 4, 'selected': False, 'text': '<p>I tried to improve the code a bit:</p>\n\n<pre><code>public T LoadEnum&lt;T&gt;(string value, T defaultValue = default(T)) where T : struct, IComparable, IFormattable, IConvertible\n{\n    if (Enum.IsDefined(typeof(T), value))\n    {\n        return (T)Enum.Parse(typeof(T), value, true);\n    }\n    return defaultValue;\n}\n</code></pre>\n'}, {'answer_id': 8086788, 'author': 'Christopher Currens', 'author_id': 721276, 'author_profile': 'https://Stackoverflow.com/users/721276', 'pm_score': 11, 'selected': True, 'text': '<h2>This feature is finally supported in C# 7.3!</h2>\n<p>The following snippet (from <a href="https://github.com/dotnet/samples/blob/3ee82879284e3f4755251fd33c3b3e533f7b3485/snippets/csharp/keywords/GenericWhereConstraints.cs#L180-L190" rel="noreferrer">the dotnet samples</a>) demonstrates how:</p>\n<pre><code>public static Dictionary&lt;int, string&gt; EnumNamedValues&lt;T&gt;() where T : System.Enum\n{\n    var result = new Dictionary&lt;int, string&gt;();\n    var values = Enum.GetValues(typeof(T));\n\n    foreach (int item in values)\n        result.Add(item, Enum.GetName(typeof(T), item));\n    return result;\n}\n</code></pre>\n<p>Be sure to set your language version in your C# project to version 7.3.</p>\n<hr />\n<p>Original Answer below:</p>\n<p>I\'m late to the game, but I took it as a challenge to see how it could be done.  It\'s not possible in C# (or VB.NET, but scroll down for F#), but <em>is possible</em> in MSIL.  I wrote this little....thing</p>\n<pre><code>// license: http://www.apache.org/licenses/LICENSE-2.0.html\n.assembly MyThing{}\n.class public abstract sealed MyThing.Thing\n       extends [mscorlib]System.Object\n{\n  .method public static !!T  GetEnumFromString&lt;valuetype .ctor ([mscorlib]System.Enum) T&gt;(string strValue,\n                                                                                          !!T defaultValue) cil managed\n  {\n    .maxstack  2\n    .locals init ([0] !!T temp,\n                  [1] !!T return_value,\n                  [2] class [mscorlib]System.Collections.IEnumerator enumerator,\n                  [3] class [mscorlib]System.IDisposable disposer)\n    // if(string.IsNullOrEmpty(strValue)) return defaultValue;\n    ldarg strValue\n    call bool [mscorlib]System.String::IsNullOrEmpty(string)\n    brfalse.s HASVALUE\n    br RETURNDEF         // return default it empty\n    \n    // foreach (T item in Enum.GetValues(typeof(T)))\n  HASVALUE:\n    // Enum.GetValues.GetEnumerator()\n    ldtoken !!T\n    call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)\n    call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)\n    callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator() \n    stloc enumerator\n    .try\n    {\n      CONDITION:\n        ldloc enumerator\n        callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()\n        brfalse.s LEAVE\n        \n      STATEMENTS:\n        // T item = (T)Enumerator.Current\n        ldloc enumerator\n        callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()\n        unbox.any !!T\n        stloc temp\n        ldloca.s temp\n        constrained. !!T\n        \n        // if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;\n        callvirt instance string [mscorlib]System.Object::ToString()\n        callvirt instance string [mscorlib]System.String::ToLower()\n        ldarg strValue\n        callvirt instance string [mscorlib]System.String::Trim()\n        callvirt instance string [mscorlib]System.String::ToLower()\n        callvirt instance bool [mscorlib]System.String::Equals(string)\n        brfalse.s CONDITION\n        ldloc temp\n        stloc return_value\n        leave.s RETURNVAL\n        \n      LEAVE:\n        leave.s RETURNDEF\n    }\n    finally\n    {\n        // ArrayList\'s Enumerator may or may not inherit from IDisposable\n        ldloc enumerator\n        isinst [mscorlib]System.IDisposable\n        stloc.s disposer\n        ldloc.s disposer\n        ldnull\n        ceq\n        brtrue.s LEAVEFINALLY\n        ldloc.s disposer\n        callvirt instance void [mscorlib]System.IDisposable::Dispose()\n      LEAVEFINALLY:\n        endfinally\n    }\n  \n  RETURNDEF:\n    ldarg defaultValue\n    stloc return_value\n  \n  RETURNVAL:\n    ldloc return_value\n    ret\n  }\n} \n</code></pre>\n<p>Which generates a function that <strong>would</strong> look like this, if it were valid C#:</p>\n<pre><code>T GetEnumFromString&lt;T&gt;(string valueString, T defaultValue) where T : Enum\n</code></pre>\n<p>Then with the following C# code:</p>\n<pre><code>using MyThing;\n// stuff...\nprivate enum MyEnum { Yes, No, Okay }\nstatic void Main(string[] args)\n{\n    Thing.GetEnumFromString(&quot;No&quot;, MyEnum.Yes); // returns MyEnum.No\n    Thing.GetEnumFromString(&quot;Invalid&quot;, MyEnum.Okay);  // returns MyEnum.Okay\n    Thing.GetEnumFromString(&quot;AnotherInvalid&quot;, 0); // compiler error, not an Enum\n}\n</code></pre>\n<p>Unfortunately, this means having this part of your code written in MSIL instead of C#, with the only added benefit being that you\'re able to constrain this method by <code>System.Enum</code>.  It\'s also kind of a bummer, because it gets compiled into a separate assembly.  However, it doesn\'t mean you have to deploy it that way.</p>\n<p>By removing the line <code>.assembly MyThing{}</code> and invoking ilasm as follows:</p>\n<pre><code>ilasm.exe /DLL /OUTPUT=MyThing.netmodule\n</code></pre>\n<p>you get a netmodule instead of an assembly.</p>\n<p>Unfortunately, VS2010 (and earlier, obviously) does not support adding netmodule references, which means you\'d have to leave it in 2 separate assemblies when you\'re debugging.  The only way you can add them as part of your assembly would be to run csc.exe yourself using the <code>/addmodule:{files}</code> command line argument.  It wouldn\'t be <em>too</em> painful in an MSBuild script.  Of course, if you\'re brave or stupid, you can run csc yourself manually each time.  And it certainly gets more complicated as multiple assemblies need access to it.</p>\n<p>So, it CAN be done in .Net.  Is it worth the extra effort?  Um, well, I guess I\'ll let you decide on that one.</p>\n<hr />\n<h3>F# Solution as alternative</h3>\n<p>Extra Credit:  It turns out that a generic restriction on <code>enum</code> is possible in at least one other .NET language besides MSIL: F#.</p>\n<pre class="lang-ml prettyprint-override"><code>type MyThing =\n    static member GetEnumFromString&lt;\'T when \'T :&gt; Enum&gt; str defaultValue: \'T =\n        /// protect for null (only required in interop with C#)\n        let str = if isNull str then String.Empty else str\n\n        Enum.GetValues(typedefof&lt;\'T&gt;)\n        |&gt; Seq.cast&lt;_&gt;\n        |&gt; Seq.tryFind(fun v -&gt; String.Compare(v.ToString(), str.Trim(), true) = 0)\n        |&gt; function Some x -&gt; x | None -&gt; defaultValue\n</code></pre>\n<p>This one is easier to maintain since it\'s a well-known language with full Visual Studio IDE support, but you still need a separate project in your solution for it. However, it naturally produces considerably different IL (the code <em>is</em> very different) and it relies on the <code>FSharp.Core</code> library, which, just like any other external library, needs to become part of your distribution.</p>\n<p>Here\'s how you can use it (basically the same as the MSIL solution), and to show that it correctly fails on otherwise synonymous structs:</p>\n<pre><code>// works, result is inferred to have type StringComparison\nvar result = MyThing.GetEnumFromString(&quot;OrdinalIgnoreCase&quot;, StringComparison.Ordinal);\n// type restriction is recognized by C#, this fails at compile time\nvar result = MyThing.GetEnumFromString(&quot;OrdinalIgnoreCase&quot;, 42);\n</code></pre>\n'}, {'answer_id': 10273741, 'author': 'expert', 'author_id': 226895, 'author_profile': 'https://Stackoverflow.com/users/226895', 'pm_score': 1, 'selected': False, 'text': '<p>I loved Christopher Currens\'s solution using IL but for those who don\'t want to deal with tricky business of including MSIL into their build process I wrote similar function in C#.</p>\n\n<p>Please note though that you can\'t use generic restriction like <code>where T : Enum</code> because Enum is special type. Therefore I have to check if given generic type is really enum.</p>\n\n<p>My function is:</p>\n\n<pre><code>public static T GetEnumFromString&lt;T&gt;(string strValue, T defaultValue)\n{\n    // Check if it realy enum at runtime \n    if (!typeof(T).IsEnum)\n        throw new ArgumentException("Method GetEnumFromString can be used with enums only");\n\n    if (!string.IsNullOrEmpty(strValue))\n    {\n        IEnumerator enumerator = Enum.GetValues(typeof(T)).GetEnumerator();\n        while (enumerator.MoveNext())\n        {\n            T temp = (T)enumerator.Current;\n            if (temp.ToString().ToLower().Equals(strValue.Trim().ToLower()))\n                return temp;\n        }\n    }\n\n    return defaultValue;\n}\n</code></pre>\n'}, {'answer_id': 16736914, 'author': 'Yahoo Serious', 'author_id': 422877, 'author_profile': 'https://Stackoverflow.com/users/422877', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Edit</strong></p>\n\n<p>The question has now superbly been answered by <a href="https://stackoverflow.com/a/28527552/422877">Julien Lebosquain</a>.\nI would also like to extend his answer with <code>ignoreCase</code>, <code>defaultValue</code> and optional arguments, while adding <code>TryParse</code> and <code>ParseOrDefault</code>.</p>\n\n<pre><code>public abstract class ConstrainedEnumParser&lt;TClass&gt; where TClass : class\n// value type constraint S ("TEnum") depends on reference type T ("TClass") [and on struct]\n{\n    // internal constructor, to prevent this class from being inherited outside this code\n    internal ConstrainedEnumParser() {}\n    // Parse using pragmatic/adhoc hard cast:\n    //  - struct + class = enum\n    //  - \'guaranteed\' call from derived &lt;System.Enum&gt;-constrained type EnumUtils\n    public static TEnum Parse&lt;TEnum&gt;(string value, bool ignoreCase = false) where TEnum : struct, TClass\n    {\n        return (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase);\n    }\n    public static bool TryParse&lt;TEnum&gt;(string value, out TEnum result, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T\n    {\n        var didParse = Enum.TryParse(value, ignoreCase, out result);\n        if (didParse == false)\n        {\n            result = defaultValue;\n        }\n        return didParse;\n    }\n    public static TEnum ParseOrDefault&lt;TEnum&gt;(string value, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T\n    {\n        if (string.IsNullOrEmpty(value)) { return defaultValue; }\n        TEnum result;\n        if (Enum.TryParse(value, ignoreCase, out result)) { return result; }\n        return defaultValue;\n    }\n}\n\npublic class EnumUtils: ConstrainedEnumParser&lt;System.Enum&gt;\n// reference type constraint to any &lt;System.Enum&gt;\n{\n    // call to parse will then contain constraint to specific &lt;System.Enum&gt;-class\n}\n</code></pre>\n\n<p>Examples of usage:</p>\n\n<pre><code>WeekDay parsedDayOrArgumentException = EnumUtils.Parse&lt;WeekDay&gt;("monday", ignoreCase:true);\nWeekDay parsedDayOrDefault;\nbool didParse = EnumUtils.TryParse&lt;WeekDay&gt;("clubs", out parsedDayOrDefault, ignoreCase:true);\nparsedDayOrDefault = EnumUtils.ParseOrDefault&lt;WeekDay&gt;("friday", ignoreCase:true, defaultValue:WeekDay.Sunday);\n</code></pre>\n\n<hr>\n\n<p><strong>Old</strong></p>\n\n<p>My old improvements on <a href="https://stackoverflow.com/a/79903">Vivek\'s answer</a> by using the comments and \'new\' developments:</p>\n\n<ul>\n<li>use <code>TEnum</code> for clarity for users</li>\n<li>add more interface-constraints for additional constraint-checking</li>\n<li>let <a href="http://msdn.microsoft.com/en-us/library/dd991317.aspx" rel="noreferrer"><code>TryParse</code></a> handle <code>ignoreCase</code> with the existing parameter\n(introduced in VS2010/.Net 4) </li>\n<li>optionally use the generic <a href="http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx" rel="noreferrer"><code>default</code> value</a> (introduced in VS2005/.Net 2)</li>\n<li>use <a href="http://msdn.microsoft.com/en-us/library/dd264739.aspx" rel="noreferrer">optional arguments</a>(introduced in VS2010/.Net 4) with default values, for <code>defaultValue</code> and <code>ignoreCase</code></li>\n</ul>\n\n<p>resulting in:</p>\n\n<pre><code>public static class EnumUtils\n{\n    public static TEnum ParseEnum&lt;TEnum&gt;(this string value,\n                                         bool ignoreCase = true,\n                                         TEnum defaultValue = default(TEnum))\n        where TEnum : struct,  IComparable, IFormattable, IConvertible\n    {\n        if ( ! typeof(TEnum).IsEnum) { throw new ArgumentException("TEnum must be an enumerated type"); }\n        if (string.IsNullOrEmpty(value)) { return defaultValue; }\n        TEnum lResult;\n        if (Enum.TryParse(value, ignoreCase, out lResult)) { return lResult; }\n        return defaultValue;\n    }\n}\n</code></pre>\n'}, {'answer_id': 17852186, 'author': 'niaher', 'author_id': 111438, 'author_profile': 'https://Stackoverflow.com/users/111438', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ve encapsulated Vivek\'s solution into a utility class that you can reuse. Please note that you still should define type constraints "where T : struct, IConvertible" on your type.</p>\n\n<pre><code>using System;\n\ninternal static class EnumEnforcer\n{\n    /// &lt;summary&gt;\n    /// Makes sure that generic input parameter is of an enumerated type.\n    /// &lt;/summary&gt;\n    /// &lt;typeparam name="T"&gt;Type that should be checked.&lt;/typeparam&gt;\n    /// &lt;param name="typeParameterName"&gt;Name of the type parameter.&lt;/param&gt;\n    /// &lt;param name="methodName"&gt;Name of the method which accepted the parameter.&lt;/param&gt;\n    public static void EnforceIsEnum&lt;T&gt;(string typeParameterName, string methodName)\n        where T : struct, IConvertible\n    {\n        if (!typeof(T).IsEnum)\n        {\n            string message = string.Format(\n                "Generic parameter {0} in {1} method forces an enumerated type. Make sure your type parameter {0} is an enum.",\n                typeParameterName,\n                methodName);\n\n            throw new ArgumentException(message);\n        }\n    }\n\n    /// &lt;summary&gt;\n    /// Makes sure that generic input parameter is of an enumerated type.\n    /// &lt;/summary&gt;\n    /// &lt;typeparam name="T"&gt;Type that should be checked.&lt;/typeparam&gt;\n    /// &lt;param name="typeParameterName"&gt;Name of the type parameter.&lt;/param&gt;\n    /// &lt;param name="methodName"&gt;Name of the method which accepted the parameter.&lt;/param&gt;\n    /// &lt;param name="inputParameterName"&gt;Name of the input parameter of this page.&lt;/param&gt;\n    public static void EnforceIsEnum&lt;T&gt;(string typeParameterName, string methodName, string inputParameterName)\n        where T : struct, IConvertible\n    {\n        if (!typeof(T).IsEnum)\n        {\n            string message = string.Format(\n                "Generic parameter {0} in {1} method forces an enumerated type. Make sure your input parameter {2} is of correct type.",\n                typeParameterName,\n                methodName,\n                inputParameterName);\n\n            throw new ArgumentException(message);\n        }\n    }\n\n    /// &lt;summary&gt;\n    /// Makes sure that generic input parameter is of an enumerated type.\n    /// &lt;/summary&gt;\n    /// &lt;typeparam name="T"&gt;Type that should be checked.&lt;/typeparam&gt;\n    /// &lt;param name="exceptionMessage"&gt;Message to show in case T is not an enum.&lt;/param&gt;\n    public static void EnforceIsEnum&lt;T&gt;(string exceptionMessage)\n        where T : struct, IConvertible\n    {\n        if (!typeof(T).IsEnum)\n        {\n            throw new ArgumentException(exceptionMessage);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 22636379, 'author': 'KarmaEDV', 'author_id': 2620046, 'author_profile': 'https://Stackoverflow.com/users/2620046', 'pm_score': 2, 'selected': False, 'text': '<p>This is my take at it. Combined from the answers and MSDN</p>\n\n<pre><code>public static TEnum ParseToEnum&lt;TEnum&gt;(this string text) where TEnum : struct, IConvertible, IComparable, IFormattable\n{\n    if (string.IsNullOrEmpty(text) || !typeof(TEnum).IsEnum)\n        throw new ArgumentException("TEnum must be an Enum type");\n\n    try\n    {\n        var enumValue = (TEnum)Enum.Parse(typeof(TEnum), text.Trim(), true);\n        return enumValue;\n    }\n    catch (Exception)\n    {\n        throw new ArgumentException(string.Format("{0} is not a member of the {1} enumeration.", text, typeof(TEnum).Name));\n    }\n}\n</code></pre>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/kxydatf9%28v=vs.110%29.aspx" rel="nofollow">MSDN Source</a></p>\n'}, {'answer_id': 28527552, 'author': 'Julien Lebosquain', 'author_id': 183367, 'author_profile': 'https://Stackoverflow.com/users/183367', 'pm_score': 8, 'selected': False, 'text': '<h1>C# ≥ 7.3</h1>\n\n<p>Starting with C# 7.3 (available with Visual Studio 2017 ≥ v15.7), this code is now completely valid:</p>\n\n<pre><code>public static TEnum Parse&lt;TEnum&gt;(string value)\n    where TEnum : struct, Enum\n{\n ...\n}\n</code></pre>\n\n<hr>\n\n<h1>C# ≤ 7.2</h1>\n\n<p>You can have a real compiler enforced enum constraint by abusing constraint inheritance. The following code specifies both a <code>class</code> and a <code>struct</code> constraints at the same time:</p>\n\n<pre><code>public abstract class EnumClassUtils&lt;TClass&gt;\nwhere TClass : class\n{\n\n    public static TEnum Parse&lt;TEnum&gt;(string value)\n    where TEnum : struct, TClass\n    {\n        return (TEnum) Enum.Parse(typeof(TEnum), value);\n    }\n\n}\n\npublic class EnumUtils : EnumClassUtils&lt;Enum&gt;\n{\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>EnumUtils.Parse&lt;SomeEnum&gt;("value");\n</code></pre>\n\n<p>Note: this is specifically stated in the C# 5.0 language specification:</p>\n\n<blockquote>\n  <p>If type parameter S depends on type parameter T then:\n  [...] It is valid for\n  S to have the value type constraint and T to have the reference type\n  constraint. Effectively this limits T to the types System.Object,\n  System.ValueType, System.Enum, and any interface type.</p>\n</blockquote>\n'}, {'answer_id': 40357283, 'author': 'Basheer AL-MOMANI', 'author_id': 4251431, 'author_profile': 'https://Stackoverflow.com/users/4251431', 'pm_score': 1, 'selected': False, 'text': '<p>I created an extension Method <code>to get integer value from enum</code> \ntake look at method implementation </p>\n\n<pre><code>public static int ToInt&lt;T&gt;(this T soure) where T : IConvertible//enum\n{\n    if (typeof(T).IsEnum)\n    {\n        return (int) (IConvertible)soure;// the tricky part\n    }\n    //else\n    //    throw new ArgumentException("T must be an enumerated type");\n    return soure.ToInt32(CultureInfo.CurrentCulture);\n}\n</code></pre>\n\n<p>this is usage </p>\n\n<pre><code>MemberStatusEnum.Activated.ToInt()// using extension Method\n(int) MemberStatusEnum.Activated //the ordinary way\n</code></pre>\n'}, {'answer_id': 45274236, 'author': 'BatteryBackupUnit', 'author_id': 684096, 'author_profile': 'https://Stackoverflow.com/users/684096', 'pm_score': 1, 'selected': False, 'text': '<p>As stated in other answers before; while this cannot be expressed in source-code it can actually be done on IL Level.\n@Christopher Currens <a href="https://stackoverflow.com/a/8086788/684096">answer</a> shows how the IL do to that.</p>\n\n<p>With <a href="https://github.com/Fody/Fody" rel="nofollow noreferrer">Fody</a>s Add-In <a href="https://github.com/Fody/ExtraConstraints" rel="nofollow noreferrer">ExtraConstraints.Fody</a> there\'s a very simple way, complete with build-tooling, to achieve this. Just add their nuget packages (<code>Fody</code>, <code>ExtraConstraints.Fody</code>) to your project and add the constraints as follows (Excerpt from the Readme of ExtraConstraints):</p>\n\n<pre><code>public void MethodWithEnumConstraint&lt;[EnumConstraint] T&gt;() {...}\n\npublic void MethodWithTypeEnumConstraint&lt;[EnumConstraint(typeof(ConsoleColor))] T&gt;() {...}\n</code></pre>\n\n<p>and Fody will add the necessary IL for the constraint to be present.\nAlso note the additional feature of constraining delegates:</p>\n\n<pre><code>public void MethodWithDelegateConstraint&lt;[DelegateConstraint] T&gt; ()\n{...}\n\npublic void MethodWithTypeDelegateConstraint&lt;[DelegateConstraint(typeof(Func&lt;int&gt;))] T&gt; ()\n{...}\n</code></pre>\n\n<p>Regarding Enums, you might also want to take note of the highly interesting <a href="https://github.com/TylerBrinkley/Enums.NET" rel="nofollow noreferrer">Enums.NET</a>.</p>\n'}, {'answer_id': 47457596, 'author': 'uluorta', 'author_id': 785915, 'author_profile': 'https://Stackoverflow.com/users/785915', 'pm_score': 0, 'selected': False, 'text': "<p>If it's ok to use direct casting afterwards, I guess you can use the <code>System.Enum</code> base class in your method, wherever necessary. You just need to replace the type parameters carefully. So the method implementation would be like:</p>\n\n<pre><code>public static class EnumUtils\n{\n    public static Enum GetEnumFromString(string value, Enum defaultValue)\n    {\n        if (string.IsNullOrEmpty(value)) return defaultValue;\n        foreach (Enum item in Enum.GetValues(defaultValue.GetType()))\n        {\n            if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;\n        }\n        return defaultValue;\n    }\n}\n</code></pre>\n\n<p>Then you can use it like:</p>\n\n<pre><code>var parsedOutput = (YourEnum)EnumUtils.GetEnumFromString(someString, YourEnum.DefaultValue);\n</code></pre>\n"}, {'answer_id': 49432554, 'author': 'DiskJunky', 'author_id': 1838819, 'author_profile': 'https://Stackoverflow.com/users/1838819', 'pm_score': 5, 'selected': False, 'text': '<p>The existing answers are true as of C# &lt;=7.2. However, there is a C# language <a href="https://github.com/dotnet/csharplang/issues/104" rel="noreferrer">feature request</a> (tied to a <a href="https://github.com/dotnet/corefx/issues/15453" rel="noreferrer">corefx</a> feature request) to allow the following;</p>\n\n<pre><code>public class MyGeneric&lt;TEnum&gt; where TEnum : System.Enum\n{ }\n</code></pre>\n\n<p>At time of writing, the feature is "In discussion" at the Language Development Meetings.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>As per <a href="https://stackoverflow.com/users/661933/nawfal">nawfal</a>\'s info, this is being introduced in C# <a href="https://learn.microsoft.com/en-us/visualstudio/releasenotes/vs2017-Preview-relnotes#csharp" rel="noreferrer">7.3</a>.</p>\n\n<p><strong>EDIT 2</strong></p>\n\n<p>This is now in C# 7.3 forward (<a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-3" rel="noreferrer">release notes</a>)</p>\n\n<p>Sample;</p>\n\n<pre><code>public static Dictionary&lt;int, string&gt; EnumNamedValues&lt;T&gt;()\n    where T : System.Enum\n{\n    var result = new Dictionary&lt;int, string&gt;();\n    var values = Enum.GetValues(typeof(T));\n\n    foreach (int item in values)\n        result.Add(item, Enum.GetName(typeof(T), item));\n    return result;\n}\n</code></pre>\n'}, {'answer_id': 50270186, 'author': 'baumgarb', 'author_id': 4587483, 'author_profile': 'https://Stackoverflow.com/users/4587483', 'pm_score': 4, 'selected': False, 'text': '<p>It should also be considered that since the release of C# 7.3 using Enum constraints is supported out-of-the-box without having to do additional checking and stuff.</p>\n\n<p>So going forward and given you\'ve changed the language version of your project to C# 7.3 the following code is going to work perfectly fine:</p>\n\n<pre><code>    private static T GetEnumFromString&lt;T&gt;(string value, T defaultValue) where T : Enum\n    {\n        // Your code goes here...\n    }\n</code></pre>\n\n<p>In case you\'re don\'t know how to change the language version to C# 7.3 see the following screenshot:\n<a href="https://i.stack.imgur.com/GMWgy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GMWgy.png" alt="enter image description here"></a></p>\n\n<p><strong>EDIT 1 - Required Visual Studio Version and considering ReSharper</strong></p>\n\n<p>For Visual Studio to recognize the new syntax you need at least version 15.7. You can find that also mentioned in Microsoft\'s release notes, see <a href="https://learn.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes#whats-new-in-157" rel="noreferrer">Visual Studio 2017 15.7 Release Notes</a>. Thanks @MohamedElshawaf for pointing out this valid question.</p>\n\n<p>Pls also note that in my case ReSharper 2018.1 as of writing this EDIT does not yet support C# 7.3. Having ReSharper activated it highlights the Enum constraint as an error telling me <em>Cannot use \'System.Array\', \'System.Delegate\', \'System.Enum\', \'System.ValueType\', \'object\' as type parameter constraint</em>. \nReSharper suggests as a quick fix to <em>Remove \'Enum\' constraint of type paramter T of method</em> </p>\n\n<p>However, if you turn off ReSharper temporarily under <em>Tools -> Options -> ReSharper Ultimate -> General</em> you\'ll see that the syntax is perfectly fine given that you use VS 15.7 or higher and C# 7.3 or higher. </p>\n'}, {'answer_id': 50596283, 'author': 'Rodney P. Barbati', 'author_id': 1588303, 'author_profile': 'https://Stackoverflow.com/users/1588303', 'pm_score': -1, 'selected': False, 'text': '<p>Just for completeness, the following is a Java solution.  I am certain the same could be done in C# as well.  It avoids having to specify the type anywhere in code - instead, you specify it in the strings you are trying to parse.</p>\n\n<p>The problem is that there isn\'t any way to know which enumeration the String might match - so the answer is to solve that problem.</p>\n\n<p>Instead of accepting just the string value, accept a String that has both the enumeration and the value in the form "enumeration.value".  Working code is below - requires Java 1.8 or later.  This would also make the XML more precise as in you would see something like color="Color.red" instead of just color="red".</p>\n\n<p>You would call the acceptEnumeratedValue() method with a string containing the enum name dot value name.  </p>\n\n<p>The method returns the formal enumerated value.</p>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\nimport java.util.function.Function;\n\n\npublic class EnumFromString {\n\n    enum NumberEnum {One, Two, Three};\n    enum LetterEnum {A, B, C};\n\n\n    Map&lt;String, Function&lt;String, ? extends Enum&gt;&gt; enumsByName = new HashMap&lt;&gt;();\n\n    public static void main(String[] args) {\n        EnumFromString efs = new EnumFromString();\n\n        System.out.print("\\nFirst string is NumberEnum.Two - enum is " + efs.acceptEnumeratedValue("NumberEnum.Two").name());\n        System.out.print("\\nSecond string is LetterEnum.B - enum is " + efs.acceptEnumeratedValue("LetterEnum.B").name());\n\n    }\n\n    public EnumFromString() {\n        enumsByName.put("NumberEnum", s -&gt; {return NumberEnum.valueOf(s);});\n        enumsByName.put("LetterEnum", s -&gt; {return LetterEnum.valueOf(s);});\n    }\n\n    public Enum acceptEnumeratedValue(String enumDotValue) {\n\n        int pos = enumDotValue.indexOf(".");\n\n        String enumName = enumDotValue.substring(0, pos);\n        String value = enumDotValue.substring(pos + 1);\n\n        Enum enumeratedValue = enumsByName.get(enumName).apply(value);\n\n        return enumeratedValue;\n    }\n\n\n}\n</code></pre>\n'}, {'answer_id': 58731308, 'author': 'Cubelaster', 'author_id': 1562834, 'author_profile': 'https://Stackoverflow.com/users/1562834', 'pm_score': 1, 'selected': False, 'text': '<p>This is my implementation. Basically, you can setup any attribute and it works. </p>\n\n<pre><code>public static class EnumExtensions\n    {\n        public static string GetDescription(this Enum @enum)\n        {\n            Type type = @enum.GetType();\n            FieldInfo fi = type.GetField(@enum.ToString());\n            DescriptionAttribute[] attrs =\n                fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];\n            if (attrs.Length &gt; 0)\n            {\n                return attrs[0].Description;\n            }\n            return null;\n        }\n    }\n</code></pre>\n'}, {'answer_id': 69573641, 'author': 'Chris F Carroll', 'author_id': 550314, 'author_profile': 'https://Stackoverflow.com/users/550314', 'pm_score': 3, 'selected': False, 'text': "<p>note that <code>System.Enum</code> <code>Parse()</code> &amp; <code>TryParse()</code> methods still have <code>where struct</code> constraints rather than <code>where Enum</code>, so that this won't compile:</p>\n<pre><code>    bool IsValid&lt;TE&gt;(string attempted) where TE : Enum\n    {\n        return Enum.TryParse(attempted, out TE _);\n    }\n</code></pre>\n<p>but this will:</p>\n<pre><code>bool Ok&lt;TE&gt;(string attempted) where TE : struct,Enum\n{\n    return Enum.TryParse(attempted, out var _)\n}\n</code></pre>\n<p>as a result, <code>where struct,Enum</code> may be preferable to just <code>where Enum</code></p>\n"}]
['https://Stackoverflow.com/questions/79126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5302/']