Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>public static class StringExtensions { /// &lt;summary&gt; /// Parses a string into an Enum /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of the Enum&lt;/typeparam&gt; /// &lt;param name="value"&gt;String value to parse&lt;/param&gt; /// &lt;returns&gt;The Enum corresponding to the stringExtensions&lt;/returns&gt; public static T EnumParse&lt;T&gt;(this string value) { return StringExtensions.EnumParse&lt;T&gt;(value, false); } public static T EnumParse&lt;T&gt;(this string value, bool ignorecase) { if (value == null) { throw new ArgumentNullException("value"); } value = value.Trim(); if (value.Length == 0) { throw new ArgumentException("Must specify valid information for parsing in the string.", "value"); } Type t = typeof(T); if (!t.IsEnum) { throw new ArgumentException("Type provided must be an Enum.", "T"); } return (T)Enum.Parse(t, value, ignorecase); } } </code></pre> <p>Useful to parse a string into an Enum.</p> <pre><code>public enum TestEnum { Bar, Test } public class Test { public void Test() { TestEnum foo = "Test".EnumParse&lt;TestEnum&gt;(); } } </code></pre> <p>Credit goes to <a href="http://geekswithblogs.net/sdorman/" rel="nofollow noreferrer">Scott Dorman</a></p> <p>--- Edit for Codeplex project ---</p> <p>I have asked Scott Dorman if he would mind us publishing his code in the Codeplex project. This is the reply I got from him:</p> <blockquote> <p>Thanks for the heads-up on both the SO post and the CodePlex project. I have upvoted your answer on the question. Yes, the code is effectively in the public domain currently under the CodeProject Open License (<a href="http://www.codeproject.com/info/cpol10.aspx" rel="nofollow noreferrer">http://www.codeproject.com/info/cpol10.aspx</a>).</p> <p>I have no problems with this being included in the CodePlex project, and if you want to add me to the project (username is sdorman) I will add that method plus some additional enum helper methods.</p> </blockquote>
 

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