Note that there are some explanatory texts on larger screens.

plurals
  1. POCreate Generic method constraining T to an Enum
    primarykey
    data
    text
    <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("T must be an enumerated type"); 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) Julien Lebosquain has recently 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>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload