Take the 2-minute tour ×

I want to make a hashtable of object references and I want a different object's reference to be the key. How can I do this in vb.net?

In java (assuming I am using the default toString method and that add() takes a string as a key and an object ref as the value) this would be something like:

hashtable.add(obj1.toString(), obj2)

I do not want to use a vb.net gethashcode() function because I want deep clones of objects to have different identifiers.

A related question is what is the default toString in vb.net?

In summery: How can I get a string that represents an object reference in vb.net?

share|improve this question

3 Answers 3

If you want the object reference to be the key of the hash table then just use the object itself.

hashtable.Add(obj1, obj2)

To answer your second question the default implementation of ToString in VB.Net is to call into Object.ToString. In .Net this will print out the type name of the underlying instance

share|improve this answer
I was trying to use the same code that you recomend, and the hashtable is using integers as the keys. –  Ray Jun 3 '11 at 15:14
@Ray why are you choosing integers? –  JaredPar Jun 3 '11 at 15:15
I did not, but that is what the Add() method did for me. –  Ray Jun 3 '11 at 15:22

You'd be far better off using a strongly typed dictionary:

Dim myDict As New Dictionary(Of myObject1Type,myObject2Type)
myDict(obj1) = obj2
share|improve this answer
You're making an assumption that the OP is using uniform types in the hash table –  JaredPar Jun 3 '11 at 15:08
Yes, that's true. –  ic3b3rg Jun 3 '11 at 15:09
Does the dictionary implicitly call the gethashcode()? –  Ray Jun 3 '11 at 15:19
This makes me think that it does use the gethashcode(): "As long as an object is used as a key in the Dictionary(Of TKey, TValue), it must not change in any way that affects its hash value" - API –  Ray Jun 3 '11 at 15:25

One possibility (though I can't say I'd recommend this for a host of reasons) is to use the .net equivalent of the VB6 ObjPtr function. Essentially, you pin the object in memory and then you can retrieve a memory address for that object (which is guaranteed to be unique).

see this posting


Alternately, if I really needed a unique identifier for an object, I'd probably extend the object and add an "ObjectID" readonly property that always returns a generated GUID for that particular instance of the object.

If those ID's weren't persisted anywhere, you could also create a singleton "IDGenerator" object that just handed out incrementing ints, and use those int's as ID's for your objects. But again, you wouldn't want to persist those int id's because they wouldn't be unique across runs of your app. Also, depending on how many objects you're instantiating, you may need to make it a long int and not just an int.

share|improve this answer

Your Answer


