Return default Enum value when Enum type is not known

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

Tags:

C#

Enums