Mary
Mary

Reputation: 211

How do I retrieve the string value of XmlEnum "Name"?

I am new to XmlEnum property. I am working on a project written in C#. I have an enum class and I wanted to map each enum to a string value. So, for example, one of the enums is:

public enum MyEnum
{
   ...,
   [XmlEnum(Name = "Failed")]
   Failure = -1,
   ...
}

My question is, in my code in a .cs file how do I retrieve the string value of the enum Failure? How do I get this string with "Failed"? Thanks in advance!

Upvotes: 1

Views: 461

Answers (1)

andrew salivan
andrew salivan

Reputation: 71

using System.Reflection;   
using System.Xml.Serialization;

string value=MyEnum.Failure.GetType()
                    .GetMember(MyEnum.Failure.ToString())
                    .FirstOrDefault()
                    ?.GetCustomAttribute<XmlEnumAttribute>()?.Name;

Upvotes: 1

Related Questions