The following extension converts a string value to a member of a specific member of an Enum unless the string value is not a member of the Enum. I intentionally did not replicate TryParse in Framework 4 and case of member must match that of a member in the Enum passed.
I am interested if anyone can see room for improvement
Usage
ExtensionCode:Public Enum UserType None Administrator Manager Developer Consultant End Enum Private Sub Demo() Dim UserType As String = "Developer" Dim UserName As String = "Kevin Gallagher" Try Dim UserPositionType As UserType = UserType.ToEnum(Of UserType)() Console.WriteLine("{0} is a {1}", UserName, UserPositionType) Catch ex As Exception MsgBox(ex.Message) End Try End Sub
Code:''' <summary> ''' Converts string value to a member of an Enum ''' </summary> ''' <typeparam name="T"></typeparam> ''' <param name="sender"></param> ''' <returns></returns> ''' <remarks> ''' An exception is thrown if member is not in Enum members ''' </remarks> <System.Diagnostics.DebuggerStepThrough()> _ <System.Runtime.CompilerServices.Extension()> _ Public Function ToEnum(Of T)(ByVal sender As String) As T Dim TheType As Type = GetType(T) If [Enum].IsDefined(GetType(T), sender) Then Return CType(System.Enum.Parse(TheType, sender, True), T) Else Dim BaseType As String = TheType.ToString Dim Pos As Integer = BaseType.IndexOf("+") Dim ErrorMsg As String = "" If Pos > -1 Then Dim EnumName As String = BaseType.Substring(Pos + 1) ErrorMsg = String.Format("'{0}' not a member of '{1}'", sender, EnumName) Else ErrorMsg = String.Format("{0} not a member of {1}", sender, TheType) End If Throw New Exception(ErrorMsg) End If End Function


Reply With Quote