Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Enum with Description

Tags:

c#

enums

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.

like image 633
Miguel Avatar asked Nov 22 '10 19:11

Miguel


People also ask

Can you convert string to enum?

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.

Can we assign string value to enum in C#?

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.

What is enum TryParse?

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.


1 Answers

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

like image 184
Adam Lear Avatar answered Oct 15 '22 16:10

Adam Lear