Modify Hash Table Value

  • Thread starter Thread starter bs
  • Start date Start date
B

bs

I have a hashtable that contains structures. Is it
possible to modify a value of one of these structures.

It only seems to work if the hash contains class objects,
not structures?
 
bs said:
I have a hashtable that contains structures. Is it
possible to modify a value of one of these structures.

It only seems to work if the hash contains class objects,
not structures?

You are right, it does not work with structures, or more generally speaking,
it does not work with value types. It only works with reference types like
classes.

The reason is that the Hashtable's Item property returns a *copy* of the
internally stored object. The following statement is invalid:

Directcast(myhash("bla"), myStructure).Prop = "test"

When you split the statement above, you get:

dim tmp as mystructure

tmp = Directcast(myhash("bla"), myStructure)
tmp.Prop = "test"

As you can see, only the copy of the structure is changed.

If possible, use a class instead of a structure. If not possible, probably
because the structure has already been defined - maybe externally - you can
write a class as a wrapper for your structure:

Class WrappedStructure
Public Value As MyStructure
End Class

Instead of adding structure objects to the hashtable, create instances of
the class and add them to the hashtable. This only makes sense if the
structure objects haven't been created before, because otherwise you'd
create another copy that is stored in the class object.
 
bs,
To continue with what Armin stated, you can retrieve the structure, modify
and put the structure back.

dim tmp as mystructure

tmp = Directcast(myhash("bla"), myStructure)
tmp.Prop = "test"
myhash("bla") = tmp ' update the hashtable with the modified structure!

However I would recommend using a class, as you have found using a class is
more intuitive.

Hope this helps
Jay
 
Back
Top