Enums and hashtables

J

John Dann

I want to save the value of an enum variable in a hashtable but a
little confused as to what I can and can't do. I sort of imagined that
I could do eg:

Dim MyEnumVar as MyEnum = MyEnum.whatever
MyHashtable.Add(MyKey, MyEnumVar)

and then retrieve the value using:

MyEnumVar2 = MyHashTable(MyKey)

But this is giving me an invalid cast error (String to Integer). And:

MyEnumVar2 = CType(MyHashTable(MyKey), MyEnum)

doesn't help. I guess I could parse the hashtable value back to the
enum, but I'm a bit puzzled as to why I can't retrieve the enum value
directly. Anyone care to comment please?

Thanks
JGD
 
J

Jay B. Harlow [MVP - Outlook]

John,
The code you show works as expected in both VS.NET 2002 & 2003.

Enum MyEnum
Whatever = 1
End Enum

Public Sub Main()
Dim MyEnumVar As MyEnum = MyEnum.Whatever
Dim MyEnumVar2 As MyEnum

Dim MyKey As String = "key"
Dim MyHashtable As New Hashtable


MyHashtable.Add(MyKey, MyEnumVar)


MyEnumVar2 = CType(MyHashTable(MyKey), MyEnum)

End Sub


Are you certain you are using the same key in both cases?

Are you certain that the value for the key is not being changed elsewhere?


Hope this helps
Jay

|I want to save the value of an enum variable in a hashtable but a
| little confused as to what I can and can't do. I sort of imagined that
| I could do eg:
|
| Dim MyEnumVar as MyEnum = MyEnum.whatever
| MyHashtable.Add(MyKey, MyEnumVar)
|
| and then retrieve the value using:
|
| MyEnumVar2 = MyHashTable(MyKey)
|
| But this is giving me an invalid cast error (String to Integer). And:
|
| MyEnumVar2 = CType(MyHashTable(MyKey), MyEnum)
|
| doesn't help. I guess I could parse the hashtable value back to the
| enum, but I'm a bit puzzled as to why I can't retrieve the enum value
| directly. Anyone care to comment please?
|
| Thanks
| JGD
 

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

Top