'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)
Solution 1:[1]
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
Solution 2:[2]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shane Ray |
| Solution 2 |
