Foo a;
try
{
// some work with a;
}
finally
{
a = null;
}
In this example, we mark object a for garbage collection.
Now suppose, we modify the code like this.
public xyz()
{
return new Foo();
}
Now in this example, the newly created object has no name, so when will it be marked for collection ? Or GC will automatically determine that it has no use, so it will try to recover it ?
EDIT :
After reading the answer, I am adding one more situation.
Foo a;
try
{
return a;
}
finally
{
a = null;
}
Now what will happen ?
if the caller of xyz assigns the result to something, then it will stick around, otherwise it will be GC’d eventually. Just need something to hold on to a reference for the object to survive GC.