1

Possible Duplicate:
Track all object references in C#

Strings are reference types. They have two parts; an object and a reference to object. For example;

string str1 = "Soner";
string str2 = str1;

str1 and str2 are references to same object, "Soner" is an object. Is there any way to find all references point to the same object? In this case, I try to find str1 and str2 just using "Soner" object?

Of course, I didn't know also how to access to string object without any reference to it. I want to know if there is a way.

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Do you mean you want to find all variables that reference a specific object in runtime at a specific point in time? – Oded Dec 24 '12 at 12:20
  • @Oded Nearly, I want to find all references to the same object. As you say, I could be only for runtime right? – Soner Gönül Dec 24 '12 at 12:22
  • And don't forget that strings are immutable and when you change them they are not the old object anymore. – Mahdi Tahsildari Dec 24 '12 at 12:30
  • @mahditahsildari Of course, but in my case there is no string changing. – Soner Gönül Dec 24 '12 at 12:32
  • look at [Mark Gravell's](http://stackoverflow.com/users/23354/marc-gravell) answer [to the same question](http://stackoverflow.com/a/707459/1471381). He says you can gatter all references of an object using SOSAssist. – Mahdi Tahsildari Dec 24 '12 at 12:29

1 Answers1

1

There isn't any built in way to get all the refercences to an object at runtime within your CLR process. The GC does not give any information about object references.

Everything you could do is building custom "tracker" that keeps references to the objects after they've been added explicitly. Jon Skeet describes the basic idea here.

Community
  • 1
  • 1
GameScripting
  • 16,092
  • 13
  • 59
  • 98
  • But, If I try `s.GetHashCode()` , `r.GetHashCode()` and `RuntimeHelpers.GetHashCode("Soner")`. First and second gave me same result but third didn't. – Soner Gönül Dec 24 '12 at 12:47
  • Go with `RuntimeHelpers.GetHashCode` if you want to use the hashcode to track the objects yourself, since `GetHashCode` can be overridden by classes (`System.String` does that) resulting in custom implementation. See [my paste](http://pastebin.com/fr6m6JHA) for an example – GameScripting Dec 24 '12 at 14:11