Getting the XmlEnumAttribute value for an Enum field

I recently had to convert an Enum back to its original Xml value so I thought I’d share the little method I wrote with you all incase you wondered how to do it yourself.

###Method

<font color="#0000FF">public static string</font> ConvertToString(<font color="#008080">Enum</font> e)
{
<font color="#008000">// Get the Type of the enum</font>
<font color="#008080">Type</font>t = e.GetType();

<font color="#008000">// Get the FieldInfo for the member field with the enums name</font>
<font color="#008080">FieldInfo</font> info = t.GetField(e.ToString(<font color="#800000">"G"</font>));

<font color="#008000">// Check to see if the XmlEnumAttribute is defined on this field</font>
<font color="#0000FF">if</font> (!info.IsDefined(<font color="#0000FF">typeof</font>(<font color="#008080">XmlEnumAttribute</font>), <font color="#0000FF">false</font>))
{
<font color="#008000">// If no XmlEnumAttribute then return the string version of the enum.</font>
<font color="#0000FF">return</font> e.ToString(<font color="#800000">"G"</font>);
}

<font color="#008000">// Get the XmlEnumAttribute</font>
<font color="#0000FF">object</font>[] o = info.GetCustomAttributes(<font color="#0000FF">typeof</font>(<font color="#008080">XmlEnumAttribute</font>), <font color="#0000FF">false</font>);
<font color="#008080">XmlEnumAttribute</font> att = (<font color="#008080">XmlEnumAttribute</font>)o[0];
<font color="#0000FF">return</font> att.Name;
}

###Example Enum Class

<font color="#0000FF">public enum </font><font color="#008080">TestEnumClass</font>
{
FirstValue = 1,
SecondValue = 2,
[System.Xml.Serialization.<font color="#008080">XmlEnum</font>(<font color="#800000">"The Third one"</font>)]
ThirdValue = 3
}

###Example usage

An Enum of TestEnumClass.FirstValue will then return “FirstValue”, while TestEnumClass.ThirdValue will return “The Third one”.

Hope you find that useful.

[tags]microsoft, .net, code, programming, sample, c#[/tags]

This entry was posted in Code. Bookmark the permalink.

One Response to Getting the XmlEnumAttribute value for an Enum field

  1. Pingback: Zorched / One Line Fix » Bug In the .NET CompactFramework XmlEnum with Whitespace

Comments are closed.