Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I'm trying to write a generic routine that will return an ENUM based on the INT value stored in the DB.

Thanks in advance

VB
Imports System.ComponentModel
Imports System.Reflection

Public Enum enColour
  <Description("BLUE")> clBlue = 1
  <Description("RED")>  clRed = 2
  <Description("GREEN")> clGreen = 3
End Enum

Public Enum enCarMake
  <Description("Ford")> cmFord = 1
  <Description("Toyota")>  cmToyota = 2
  <Description("Skoda")> cmSkoda = 3
End Enum


Public Sub LoadFromDB 
  Dim myENUMColour AS enColour
  Dim myENUMMake As enCarMake

  With rdrLoadFromTable
    ReturnENUMFromInt(CInt(.Item("Colour")), myENUMColour)
    ReturnENUMFromInt(CInt(.Item("CarMake")), myENUMMake)
  End With
End Sub

Public Sub ReturnENUMFromInt(pIntValueFromDB AS Integer, pReturnValue AS [ENUM])
  'LOOKING FOR HELP HERE...

  pReturnValue = CType(pIntValueFromDB, pReturnValue.GetType) 
End Sub;
Posted
Comments
CPallini 8-Sep-14 2:55am    
What is your problem?

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
 
Share this answer
 
Try Enum.TryParse[^], should do what you want.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900