The following generic static method takes a string and returns an enum.
It nicely ignores case since I set the ignoreCase parameter to true.
However, I also want to test if the enum exists, but the enum.IsDefined method to do this doesn't seem to have an ignoreCase parameter.
How can I test if the enum is defined or not and at the same ignore case?
using System; namespace TestEnum2934234 { class Program { static void Main(string[] args) { LessonStatus lessonStatus = StringHelpers.ConvertStringToEnum<LessonStatus>("prepared"); ReportStatus reportStatus = StringHelpers.ConvertStringToEnum<ReportStatus>("finished"); Console.WriteLine(lessonStatus.ToString()); Console.WriteLine(reportStatus.ToString()); Console.ReadLine(); } } public static class StringHelpers { public static T ConvertStringToEnum<T>(string text) { if (Enum.IsDefined(typeof(T), text)) //does not have ignoreCase parameter return (T)Enum.Parse(typeof(T), text, true); else return default(T); } } public enum LessonStatus { Defined, Prepared, Practiced, Recorded } public enum ReportStatus { Draft, Revising, Finished } }
Enum members have to start with an alphabetic character. Specifically, I know you can use an underscore as the first char. IE, enum MyEnum { _One = 1 } is valid. Not really sure this exactly wrong, but it made the assumption that anything outside the range of '0' to '9' and '-' is a valid alphabetic character.
Enum 's valueOf(String) Method Careful, the strings passed to valueOf are case sensitive!
If value is the string representation of the name of an enumeration value, the comparison of value with enumeration names is case-sensitive.
Enum constants are case sensitive.
public enum MyEnum { Bar, Foo } class Program { static void Main(string[] args) { var containsFoo = Enum.GetNames(typeof(MyEnum)).Any(x => x.ToLower() == "foo"); Console.WriteLine(containsFoo); } }
Along with @Darin's answer, in .NET 4.0, the Enum type now has a TryParse method:
MyEnum result; Enum.TryParse("bar", true, out result);
The important thing to remember is that there is a fundamental difference in the behaviour of Parse vs TryParse. Parse methods will throw exceptions. TryParse methods will not. This is quite important to know if you are potentially trying to parse many items.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With