I can't find a clear answer for this. If I instantiate a reference type inside a method but do not store it on any class variable, how long does this reference live on the heap? Is it marked as garbage on the method return and eventually get cleared by the Garbage collector?
void DoSomeStuff()
{
var myRefInstance = new Object();
}
Objects that are not reachable are marked as collectable. When the object is collected depends on the GC; if there is no memory pressure it might never be collected until the application ends.
Its important to note that the rule is "Object is not reachable", not that there is no references pointing at it, which is not the same:
void Foo() {
var a = new A();
var b = new B();
a.b = b;
b.a = a; }
Both a
and b
will be marked as unreachable when Foo
exits even though both would have a reference counter greater than 0.