Monday, August 23, 2010

How do I get the reference count of a CLR object ?

A customer asked the rather enigmatic question (with no context):
Is there a way to get the reference count of an object in .Net?
Thanks,
Bob Smith
Senior Developer
Contoso
The CLR does not maintain reference counts, so there is no reference count to "get". The garbage collector only cares about whether an object has zero references or at least one reference. It doesn't care if there is one, two, twelve, or five hundred—from the point of view of the garbage collector, one is as good as five hundred.
The customer replied,
I am aware of that, yet the mechanism is somehow implemented by the GC...
What I want to know is whether at a certain point there is more then one variable pointing to the same object.
As already noted, the GC does not implement the "count the number of references to this object" algorithm. It only implements the "Is it definitely safe to reclaim the memory for his object?" algorithm. A null garbage collector always answers "No." A tracing collector looks for references, but it only cares whether it found one, not how many it found.
The discussion of "variables pointing to the same objects" is somewhat confused, because you can have references to an object from things other than variables. Parameters to a method contain references, the implicit this is also a reference, and partially-evaluated expressions also contain references. (During execution of the line string s = o.ToString();, at the point immediately after o.ToString() returns and before the result is assigned to s, the string has an active reference but it isn't stored in any variable.) And as we saw earlier, merely storing a reference in a variable doesn't prevent the object from being collected.
Read more: The old new thing