Jake
Jake

Reputation: 11430

Return default Enum value when Enum type is not known

I have a method that attempts to match string to DescriptionAttribute of enum values and then return the enum value. In case a match is not found, it should return a default value, which I thought I could just return 0. But it's not going to happen...

private Enum GetEnumFromDescription(Type enumType, string description)
{
      var enumValues = Enum.GetValues(enumType);

      foreach (Enum e in enumValues)
      {
          if (string.Compare(description, GetDescription(e), true) == 0)
                    return e;
      }

      return 0; // not compiling
}

How should I code the above?

Upvotes: 9

Views: 7916

Answers (4)

Amol Hegana
Amol Hegana

Reputation: 157

default(T) will work for this. Get the type and use default. By default first element will be taken as Default value

Upvotes: 1

hazzik
hazzik

Reputation: 13344

I believe that the correct approach is

(Enum)Enum.ToObject(enumType, 0)

Because

  • Activator.CreateInstance is generic solution for all value types and Enum.ToObject is a specific solution for enums, so Enum.ToObject declares clear intentions of the code.
  • Enum.ToObject probably works faster than Activator.CreateInstance
  • Enum.ToObject is used inside Enum.GetValues to retrieve values.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500765

You can use

return (Enum) Activator.CreateInstance(enumType);

This will give you the default value for the type - which is what you want.

EDIT: I'd expected that you'd know the type at compile time, in which case generics are a good approach. Even though that appears not to be the case, I'll leave the rest of this answer in case it's of any use to someone else.

Alternatively, you could use Unconstrained Melody which already contains something like this functionality in a more efficient, type-safe form :)

MyEnum value;
if (Enums.TryParseDescription<MyEnum>(description, out value))
{
    // Parse successful
}

value will be set to the "0" value if the parse operation isn't successful.

Currently it's case-sensitive, but you could easily create a case-insensitive version. (Or let me know and I can do so.)

Upvotes: 16

clearpath
clearpath

Reputation: 956

Maybe this will work

return (Enum)enumValues[0];

Upvotes: 0

Related Questions