Is there any way of getting an unique identifier of an instance? GetHashCode() is same for 2 references pointing to the same instance. However, 2 different instances can (quite early) get same hash code:
Hashtable hashCodesSeen = new Hashtable();
LinkedList<object> l = new LinkedList<object>();
int n = 0;
while (true)
{
object o = new object();
// remember object so that they don't get collected
// this does not make any difference though :(
l.AddFirst(o);
int hashCode = o.GetHashCode();
n++;
if (hashCodesSeen.ContainsKey(hashCode))
{
// same hashCode seen twice for DIFFERENT objects (n is as low as 5322)
Console.WriteLine("Hashcode seen twice: " + n + " (" + hashCode + ")");
break;
}
hashCodesSeen.Add(hashCode, null);
}
I'm writing a debugging addin and I need to get some kind of ID for a reference which is unique during the run of the program.
I already managed to get internal ADDRESS of the instance, which is unique until the GC compacts the heap (= moves the objects = changes the addresses).
This thread might be related. Thanks for any advice.
[edit] Hi, thanks everyone for responses. I should have stated more clearly that the objects are not under my control as I am accessing objects in a program being debugged using the debugger API. If I was in control of the objects, adding my own unique identifiers would be trivial.
I wanted the unique ID for building a hashtable ID -> object, to be able to lookup already seen objects. For now I solved it like this:
build a hashtable: 'hashCode' -> (list of objects with hash code == 'hashCode')
find if object seen(o) {
candidates = hashtable[o.GetHashCode()] // objects with same hashCode
if no candidates, the object is new
if some candidates, compare their addresses to o.Address
if no address equal (the hash code was just a coincidence) -> o is new
if some address equal, o already seen
}