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?
The DEFAULT attribute causes an ENUM data type to have a default value when a value is not specified. In other words, we can say that INSERT statement does not have to include a value for this field because if it does not include then the value following DEFAULT will be inserted.
The default value of an enumeration type E is the value produced by expression (E)0 , even if zero doesn't have the corresponding enum member.
The default value of an enum E is the value produced by the expression (E)0 . Without overriding the default values, printing default(E) returns Foo since it's the first-occurring element.
By default, the value of the first enumerator is zero if it is implicitly defined. The value of each subsequent implicitly-defined enumerator is the value of the previous enumerator + 1. (Optional) The name of a variable of the enumeration type.
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.)
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With