Return value by default Return value when the type of Enum is not known

I have a method that tries to map a string to the DescriptionAttribute attribute of enum values, and then returns the enum value. If a match is not found, it should return a default value, which, as I thought, I can simply return 0. But this will not 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 do I code above?

+6
source share
3 answers

you can use

 return (Enum) Activator.CreateInstance(enumType); 

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

EDIT: I expected you to recognize the type at compile time, in which case generics are a good approach. Although this does not seem to be the case, I will leave the rest of this answer in case it is useful to someone else.

Alternatively, you can use Unconstrained Melody , which already contains something like this function in a more efficient and safe form :)

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

value will be set to "0" if the parsing operation is not successful.

It is currently case sensitive, but you can easily create a case-insensitive version. (Or let me know, and I can do it.)

+13
source

I believe the right approach

 (Enum)Enum.ToObject(enumType, 0) 

Because the

  • Activator.CreateInstance is a general solution for all types of values, and Enum.ToObject is a specific solution for enumerations, therefore Enum.ToObject declares clear intentions of the code.
  • Enum.ToObject is faster than Activator.CreateInstance
  • Enum.ToObject used internally by Enum.GetValues to retrieve values.
+1
source

Maybe it will work

 return (Enum)enumValues[0]; 
0
source

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


All Articles