Suppose I have
void foo () {
Bar bar = new Bar(); // bar is never referred to after this line
// (1)
doSomethingWithoutBar();
}
At (1), is the object bar is pointing to eligible for garbage collection? Or does bar have to fall out of scope as well? Does it make a difference if GC.Collect is called by doSomethingWithoutBar?
This is relevant to know if Bar has a (C#) destructor or something funky like that.
Objects can become eligible for garbage collection as soon as it’s certain that they will no longer be used. It’s entirely possible that
barwill be garbage collected before the variable goes out of scope.Proof:
Run in Release Mode (because it doesn’t get collected in Debug Mode).
Output:
It also works on ideone which uses Mono. The output is the same.