It seems a little over-kill to create your own function for doing this,
Enum.Parse
(or
Enum.TryParse
) or even a
CType
call will do this for you.
But if your circumstances are such that you need a generic method for this, then maybe something like this will do the trick for you;
Module Module1
Public Enum Color
Red
Green
Blue
End Enum
Public Enum CarMake
Ford
Toyota
Skoda
End Enum
Sub Main()
Dim color As Color = ToEnum(Of Color)(1)
Dim carMake as CarMake ToEnum(Of CarMake)(2)
End Sub
Public Function ToEnum(Of T As Structure)(ByVal arg As Integer) As T
If [Enum].IsDefined(GetType(T), arg) Then
Return [Enum].Parse(GetType(T), arg.ToString())
Else
Throw New ArgumentException(String.Format("'{0}' is not defined in enumeration {1}", arg, GetType(T).FullName))
End If
End Function
End Module
Hope this helps,
Fredrik