Convert string back to enumeration

Is there a cleaner, smarter way to do this?

I click on the DB to get the data to fill the object and convert the value of the database row back to its enumeration (we can assume that all the values โ€‹โ€‹in the database are indeed the values โ€‹โ€‹in the corresponding enumeration)

The line in question is the line below that sets EventLog.ActionType ... the reason I started to question my method is that after the equal sign VS2010 continues to try to redefine what I type by setting this: "= EventActionType ("

using (..<snip>..) { while (reader.Read()) { // <snip> eventLog.ActionType = (EventActionType)Enum.Parse(typeof(EventActionType), reader[3].ToString()); ...etc... 
+4
source share
5 answers

As far as I know, this is the best way to do this. I installed a utility class to wrap this functionality with methods that make this look cleaner.

  /// <summary> /// Convenience method to parse a string as an enum type /// </summary> public static T ParseEnum<T>(this string enumValue) where T : struct, IConvertible { return EnumUtil<T>.Parse(enumValue); } /// <summary> /// Utility methods for enum values. This static type will fail to initialize /// (throwing a <see cref="TypeInitializationException"/>) if /// you try to provide a value that is not an enum. /// </summary> /// <typeparam name="T">An enum type. </typeparam> public static class EnumUtil<T> where T : struct, IConvertible // Try to get as much of a static check as we can. { // The .NET framework doesn't provide a compile-checked // way to ensure that a type is an enum, so we have to check when the type // is statically invoked. static EnumUtil() { // Throw Exception on static initialization if the given type isn't an enum. Require.That(typeof (T).IsEnum, () => typeof(T).FullName + " is not an enum type."); } public static T Parse(string enumValue) { var parsedValue = (T)System.Enum.Parse(typeof (T), enumValue); //Require that the parsed value is defined Require.That(parsedValue.IsDefined(), () => new ArgumentException(string.Format("{0} is not a defined value for enum type {1}", enumValue, typeof(T).FullName))); return parsedValue; } public static bool IsDefined(T enumValue) { return System.Enum.IsDefined(typeof (T), enumValue); } } 

Using these utility methods, you can simply say:

  eventLog.ActionType = reader[3].ToString().ParseEnum<EventActionType>(); 
+11
source

You can use extension methods to give your syntactic sugar some syntactic sugar. You can even use these generalized extension methods.

This is the code I'm talking about: http://geekswithblogs.net/sdorman/archive/2007/09/25/Generic-Enum-Parsing-with-Extension-Methods.aspx

  public static T EnumParse<T>(this string value) { return EnumHelper.EnumParse<T>(value, false); } public static T EnumParse<T>(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"); } T enumType = (T)Enum.Parse(t, value, ignoreCase); return enumType; } SimpleEnum enumVal = Enum.Parse<SimpleEnum>(stringValue); 
+5
source

You can use the extension method as follows:

 public static EventActionType ToEventActionType(this Blah @this) { return (EventActionType)Enum.Parse(typeof(EventActionType), @this.ToString()); } 

And use it like:

 eventLog.ActionType = reader[3].ToEventActionType(); 

Where Blah above is the type of reader [3].

+3
source

You can get any enumeration value, not just an EventActionType , as in your case using the followin method.

 public static T GetEnumFromName<T>(this object @enum) { return (T)Enum.Parse(typeof(T), @enum.ToString()); } 

You can call him

 eventLog.ActionType = reader[3].GetEnumFromName<EventActionType>() 

This is a more general approach.

0
source

@StriplingWarrior's answer did not work on the first try, so I made some changes:

Helpers /EnumParser.cs

 namespace MyProject.Helpers { /// <summary> /// Utility methods for enum values. This static type will fail to initialize /// (throwing a <see cref="TypeInitializationException"/>) if /// you try to provide a value that is not an enum. /// </summary> /// <typeparam name="T">An enum type. </typeparam> public static class EnumParser<T> where T : struct, IConvertible // Try to get as much of a static check as we can. { // The .NET framework doesn't provide a compile-checked // way to ensure that a type is an enum, so we have to check when the type // is statically invoked. static EnumParser() { // Throw Exception on static initialization if the given type isn't an enum. if (!typeof (T).IsEnum) throw new Exception(typeof(T).FullName + " is not an enum type."); } public static T Parse(string enumValue) { var parsedValue = (T)Enum.Parse(typeof (T), enumValue); //Require that the parsed value is defined if (!IsDefined(parsedValue)) throw new ArgumentException(string.Format("{0} is not a defined value for enum type {1}", enumValue, typeof(T).FullName)); return parsedValue; } public static bool IsDefined(T enumValue) { return Enum.IsDefined(typeof (T), enumValue); } } } 

Extension Cords /ParseEnumExtension.cs

 namespace MyProject.Extensions { public static class ParseEnumExtension { /// <summary> /// Convenience method to parse a string as an enum type /// </summary> public static T ParseEnum<T>(this string enumValue) where T : struct, IConvertible { return EnumParser<T>.Parse(enumValue); } } } 
0
source

Source: https://habr.com/ru/post/1345106/


All Articles