1) From the code of
Factory
we can see that a new object is created and assigned to
t
. This reference is returned and goes out of scope, but as it is assigned to
anotherObj
,
anotherObj
references the same instance. On each loop iteration, this variable goes out of scope (as it is declared insider loop); the referenced instance looses all references and is scheduled for removal. In each iteration of the loop a brand new instance is created, is shown and is scheduled for removal.
2) More exactly, GC performs destruction of object and reclaiming the memory according to its own strategy. You cannot assume any particular moment of type when it happens (and any code based on such assumption is incorrect). This behavior can be observed by creation a destructor and logging its calls. Also, this behavior can be modified by using
System.GC.Collect
, see
http://msdn.microsoft.com/en-us/library/system.gc.aspx[
^]. It is not recommended to do so unless you have a really
Cunning Plan :-).
Notes:
Due to this GC behavior, the activity of writing of destructors makes little sense. With .NET, they are used pretty rarely.
Loosing all references to the object is not a trivial condition. Consider object A holds a reference to object B, object B holds a reference to object C, and object C holds a reference to object A. Consider you loose all other references to any of these objects except those circular references. Will these three object destroyed? Don't worry, the will, despite the fact they seemingly protect each other from destruction. They will be destroyed because there is no a way to access them from any actual code which could possibly be run later. So, GC mechanism is not trivial at all.
—SA