4

Is there a cleaner, more clever way to do this?

I'm hitting a DB to get data to fill an object and am converting a database string value back into its enum (we can assume that all values in the database are indeed values in the matching enum)

The line in question is the line below that sets EventLog.ActionType...the reason I began to question my method is because after the equals sign, VS2010 keeps trying to override what I'm typing by putting this: "= EventActionType("

using (..<snip>..)
{
  while (reader.Read())
  {
     // <snip>
     eventLog.ActionType = (EventActionType)Enum.Parse(typeof(EventActionType), reader[3].ToString());

...etc...
user7116
  • 63,008
  • 17
  • 141
  • 172
J Benjamin
  • 4,722
  • 6
  • 29
  • 39

5 Answers5

11

As far as I know, this is the best way to do it. I've set up a utility class to wrap this functionality with methods that make this look cleaner, though.

    /// <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);
    }

}

With these utility methods, you can just say:

 eventLog.ActionType = reader[3].ToString().ParseEnum<EventActionType>();
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • ya that's what I thought too...might be some Intellisense wonkiness or maybe an extension freaking out but it's like when I type the equals sign and continue to the value side, VS automatically puts "EventActionType(" as if it's trying to treat the enum like a normal method or something...ah well :) guess it can just be one of those little things that annoy me every day hehe – J Benjamin Mar 24 '11 at 15:13
  • that's pretty awesome...definitely going into my bag o' tricks! thanks – J Benjamin Mar 24 '11 at 15:59
  • Old question I know, but what namespace is Require part of? Googling for Require namespace yields a lot of false results. – MattR Feb 05 '15 at 11:25
  • @MattR: Require.That() => http://stackoverflow.com/questions/4892548/confusion-with-parsing-an-enum/4892571#comment5443975_4892571 – StriplingWarrior Feb 05 '15 at 16:29
5

You can use extension methods to give some syntactic sugar to your code. You can even made this extension methods generics.

This is the kind of 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);
Jonathan
  • 11,809
  • 5
  • 57
  • 91
3

Could use an extension method like so:

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].

CodeNaked
  • 40,753
  • 6
  • 122
  • 148
0

@StriplingWarrior's answer didn't work at first try, so I made some modifications:

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);
        }
    }
}

Extensions/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);
        }
    }
}
Leonel Sanches da Silva
  • 6,972
  • 9
  • 46
  • 66
0

You could get any enum value back, not just EventActionType as in your case with the followin method.

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

You can call it then,

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

This is a more generic approach.

nawfal
  • 70,104
  • 56
  • 326
  • 368