M.Efe Ozer’s Weblog

October 31, 2008

Get Enum Values : as String or as EnumValue

Filed under: .Net, Code Stuff, Notes to Myself — Tags: , , — Mehmet Efe Ozer @ 2:44 pm

It is note to myself

Original article here : http://blog.waynehartman.com/articles/84.aspx

 

Sample Enum :

Public Enum ReturnMessage As Byte

    <System.ComponentModel.Description(“msgSucceed”), _
        System.ComponentModel.Category(“ReturnMessage”)> _
        Successfull
    <System.ComponentModel.Description(“CodeNotFound”), _
        System.ComponentModel.Category(“ReturnMessage”)> _
        FieldCodeNotFound
    <System.ComponentModel.Description(“IsBlocked”), _
        System.ComponentModel.Category(“ReturnMessage”)> _
        FieldCodeBlocked
    <System.ComponentModel.Description(“msgNotSucceed”), _
        System.ComponentModel.Category(“ReturnMessage”)> _
        Failed
End Enum

 

StringValueOf :

''' <summary>
    ''' Get String Value of Enum Values
    ''' </summary>
    ''' <param name="value">example: returnMessage.FieldCodeNotFound returns "CodeNotFound"</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function stringValueOf(ByVal value As System.Enum) As String
        Dim fi As Reflection.FieldInfo = value.GetType().GetField(value.ToString())
        Dim attributes() As System.ComponentModel.DescriptionAttribute  _ 
= CType(fi.GetCustomAttributes(GetType(System.ComponentModel.DescriptionAttribute), False) _
, System.ComponentModel.DescriptionAttribute())
        If attributes.Length > 0 Then
            Return attributes(0).Description
        Else
            Return value.ToString()
        End If
    End Function

 

EnumValueOf :

''' <summary>
''' Returns Enum Value of given string
''' </summary>
''' <param name="value">example :"CodeNotFound"</param>
''' <param name="enumType">example:ReturnMessage</param>
''' <returns>example : returnmessage.FieldCodeNotFound</returns>
''' <remarks></remarks>

Public Function enumValueOf(ByVal value As String, ByVal enumType As Type) As Object
    Dim names As List(Of String) = System.Enum.GetNames(enumType).ToList

    Dim result As List(Of String) = (From filtered As String In names _
                                       Where value.ToLowerInvariant.Contains(filtered.ToLowerInvariant) _
                                Select filtered Order By filtered Descending).ToList
    If result.Count = 0 Then

        Return Nothing
    Else
        Return System.Enum.Parse(enumType, result(0))
    End If

    End Function

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.