I am currently implementing an associacion of strings and enums based on this suggestion. That being, I have a Description
attribute associated with every enum element. On that page there is also a function which returns the description's string based on the given enum. What I would like to implement now is the reverse function, that is, given an input string lookup the enum with the corresponding description if it exists, returning null otherwise.
I have tried (T) Enum.Parse(typeof(T), "teststring")
but it throws an exception.
Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.
Using string-based enums in C# is not supported and throws a compiler error. Since C# doesn't support enum with string value, in this blog post, we'll look at alternatives and examples that you can use in code to make your life easier. The most popular string enum alternatives are: Use a public static readonly string.
C# Enum TryParse() Method The TryParse() method converts the string representation of one or more enumerated constants to an equivalent enumerated object. Firstly, set an enum. enum Vehicle { Bus = 2, Truck = 4, Car = 10 }; Now, let us declare a string array and set some values.
You have to write your own reverse method. The stock Parse() method obviously doesn't know about your description attributes.
Something like this should work:
public static T GetEnumValueFromDescription<T>(string description)
{
MemberInfo[] fis = typeof(T).GetFields();
foreach (var fi in fis)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0 && attributes[0].Description == description)
return (T)Enum.Parse(typeof(T), fi.Name);
}
throw new Exception("Not found");
}
You'll want to find a better thing to do than throw an exception if the enum value wasn't found, though. :)
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