enum problems

P

Perecli Manole

I need to store an enum datatype in a variable and then reference it members
from the variable. I have tried this but it does not work.

Private Enum enuTest1 As Byte
Opt1 = 0
Opt2 = 1
Opt3 = 2
End Enum

Private Enum enuTest2 As Byte
Opt1 = 5
Opt2 = 6
Opt3 = 7
End Enum

Private Sub Test()

Dim a As Type = GetType(enuTest1)
Dim b As Byte = a.Opt2

End Sub

I need b to get the value of 1 since Opt2 in enuTest1 is 1.
However if I put GetType(enuTest2) in a then b should be 6

Thanks
Perry
 
P

Perecli Manole

What is that? You did not read the comment after the code snipit.
The reason for using variable a is because a will hold an unknown
enumeration which will be suplied by the user (i.e. enuTest1 or enuTest2).
In your example the the enumeration is hard coded.

Perry
 
M

Mythran

Perecli Manole said:
I need to store an enum datatype in a variable and then reference it
members from the variable. I have tried this but it does not work.

Private Enum enuTest1 As Byte
Opt1 = 0
Opt2 = 1
Opt3 = 2
End Enum

Private Enum enuTest2 As Byte
Opt1 = 5
Opt2 = 6
Opt3 = 7
End Enum

Private Sub Test()

Dim a As Type = GetType(enuTest1)
Dim b As Byte = a.Opt2

End Sub

I need b to get the value of 1 since Opt2 in enuTest1 is 1.
However if I put GetType(enuTest2) in a then b should be 6

Thanks
Perry

Try this :)

Imports System.Reflection

Class Class1
Private Enum enuTest1 As Byte
Opt1 = 0
Opt2 = 1
Opt3 = 2
End Enum

Private Enum enuTest2 As Byte
Opt1 = 5
Opt2 = 6
Opt3 = 7
End Enum

Public Shared Sub Start()
Test(GetType(enuTest1), "Opt2")
End Sub

Public Shared Sub Test( _
ByVal EnumType As Type, _
ByVal MemberName As String _
)
If Not EnumType.IsEnum
Throw New ArgumentException( _
"Expected an enum type, received " & EnumType.Name & ".", _
"EnumType" _
)
End If

Dim fieldInfo As FieldInfo = EnumType.GetField(MemberName)
Dim v As Object = fieldInfo.GetValue(Nothing)
Console.WriteLine(CInt(v))
End Sub
End Class


HTH,
Mythran
 
H

hav

IEnumerator interface exposed by all collections - returns object you
can GetNext GetEnumerator and reset. dim ALEnum AS IEnumerator
ALEnum = AList.GetEnumerator

dim AItems as IEnu.....tor
aItem = aList.GetEn..r
while aitems.movenext
{ process item aItems.Current }
end while

hth


Henz
 
S

schneider

So you are getting the string from the user? You did not state that. Are you
getting a fully qualified enum value?
If you are starting from a string version of the enum value then you should
use Enum.Parse method to get the specified enumeration value.
If the enumeration type could be either #1 or #2 you may need to do further
checks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top