vmb
vmb

Reputation: 3028

Enum with Spaces .TryParse not working - C#

I have one enum type which is having items with spaces

     public enum Enum1
    {
        [Description("Test1 Enum")]
        Test1Enum,
        [Description("Test2 Enum")]
        Test2Enum,
        [Description("Test3Enum")]
        Test3Enum, 
    }

   public void TestMethod(string testValue)
     {
        Enum1 stEnum;
        Enum.TryParse(testValue, out stEnum);
        switch (stEnum)
        {
            case ScriptQcConditonEnum.Test1Enum:
                Console.Log("Hi");
                break;
        }
      }

When i using Enum.TryParse(testValue, out stEnum) ,It always returns first element.

 // Currently stEnum returns Test1Enum which is wrong
    Enum.TryParse("Test2 Enum", out stEnum) 

Upvotes: 3

Views: 3954

Answers (3)

Warger
Warger

Reputation: 1

Based on the idea of @csharpbd, I thought the following approach.

public static T ParseEnum<T>(string valueToParse)
{
    // Check if it is an enumerated
    if (typeof(T).IsEnum)
    {
        // Go through all the enum
        foreach (T item in (T[])Enum.GetValues(typeof(T)))
        {
            System.Reflection.FieldInfo fieldInfo = item.GetType().GetField(item.ToString());

            // Before doing anything else we check that the name match
            if (fieldInfo.Name == valueToParse)
            {
                return item;
            }

            DescriptionAttribute[] descriptionAttributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

            // Check if the description matches what we are looking for.
            if (descriptionAttributes.Length > 0 && descriptionAttributes[0].Description == valueToParse)
            {
                return item;
            }
        }

        throw new ArgumentException("Enum cannot be found", valueToParse);
    }
    else
    {
        throw new InvalidOperationException("The object is not an enum");
    }
}

Therefore, you can call him:

Enum1 stEnum = ParseEnum<Enum1>(testValue);

Upvotes: 0

csharpbd
csharpbd

Reputation: 4076

You can parse Enum from Enum description but you need to retrieve Enum value from description. Please check below example, that retrieve Enum value from Enum description and parse it as you want.

Enum value from Enum description:

public T GetValueFromDescription<T>(string description)
    {
        var type = typeof(T);
        if (!type.IsEnum) throw new InvalidOperationException();
        foreach (var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute != null)
            {
                if (attribute.Description == description)
                    return (T)field.GetValue(null);
            }
            else
            {
                if (field.Name == description)
                    return (T)field.GetValue(null);
            }
        }
        throw new ArgumentException("Not found.", "description");
        // or return default(T);
    }

Example of parse:

Enum.TryParse(GetValueFromDescription<Enum1>("Test2 Enum").ToString(), out stEnum);

Upvotes: 5

Shane Ray
Shane Ray

Reputation: 1469

Enum.TryParse trys to parse the string based on the enum value not description. If your requirement is to parse based on description you need to use reflection to get the attribute value. How to do this has already been answered in this SO question: Finding an enum value by its Description Attribute

Upvotes: 1

Related Questions