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?
You can use
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 🙂
valuewill 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.)