2

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?

Ray
  • 21
  • 2

3 Answers3

2

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

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

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

http://forums.devx.com/showthread.php?t=122407

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.

DarinH
  • 4,868
  • 2
  • 22
  • 32
0

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

Dim myDict As New Dictionary(Of myObject1Type,myObject2Type)
myDict(obj1) = obj2
ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
  • You're making an assumption that the OP is using uniform types in the hash table – JaredPar Jun 03 '11 at 15:08
  • 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 03 '11 at 15:25