public static class StringExtensions {
///
/// Parses a string into an Enum
///
/// The type of the Enum
/// String value to parse
/// The Enum corresponding to the stringExtensions
public static T EnumParse(this string value) {
return StringExtensions.EnumParse(value, false);
}
public static T EnumParse(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);
}
}
Useful to parse a string into an Enum.
public enum TestEnum
{
Bar,
Test
}
public class Test
{
public void Test()
{
TestEnum foo = "Test".EnumParse();
}
}
Credit goes to Scott Dorman
--- Edit for Codeplex project ---
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:
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 (http://www.codeproject.com/info/cpol10.aspx).
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.