Retrieve enum value based on XmlEnumAttribute name value

Posted by CletusLoomis on Stack Overflow See other posts from Stack Overflow or by CletusLoomis
Published on 2010-06-15T16:32:03Z Indexed on 2010/06/15 16:42 UTC
Read the original article Hit count: 962

Filed under:
|
|
|

I need a Generic function to retrieve the name or value of an enum based on the XmlEnumAttribute "Name" property of the enum. For example I have the following enum defined:

Public Enum Currency
   <XmlEnum("00")> CDN = 1
   <XmlEnum("01")> USA= 2
   <XmlEnum("02")> EUR= 3
   <XmlEnum("03")> JPN= 4
End Enum

The first Currency enum value is 1; the enum name is "CDN"; and the XMLEnumAttribute Name property value is "00".

If I have the enum value, I can retrieve the XmlEnumAttribute "Name" value using the following generic function:

Public Function GetXmlAttrNameFromEnumValue(Of T)(ByVal pEnumVal As T) As String

        Dim type As Type = pEnumVal.GetType
        Dim info As FieldInfo = type.GetField([Enum].GetName(GetType(T), pEnumVal))
        Dim att As XmlEnumAttribute = CType(info.GetCustomAttributes(GetType(XmlEnumAttribute), False)(0), XmlEnumAttribute) 'If there is an xmlattribute defined, return the name

        Return att.Name
    End Function

So using the above function, I can specify the Currency enum type, pass a value of 1, and the return value will be "00".

What I need is a function to perform if the opposite. If I have the XmlEnumAttribute Name value "00", I need a function to return a Currency enum with a value of 1. Just as useful would be a function that would return the enum name "CDN". I could then simply parse this to get the enum value.

Any assistance would be appreciated.

© Stack Overflow or respective owner

Related posts about c#

Related posts about vb.net