Enums and hashtables

  • Thread starter Thread starter John Dann
  • Start date Start date
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
 
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
 
Back
Top