The object referenced by tempCollection
turns into garbage immediately after the last mentioning of tempCollection
in the method body - i.e. sometimes long before the method returns control.
GC collects objects after they become unreachable - i.e. after they, directly or indirectly, can not be seen from the so-called. roots - static fields, local variables and a couple more specific places. As soon as the object becomes unreachable - GC can calmly kill it.
Suppose your method looks like this:
public ICollection<Entity> GetData() { ICollection<Entity> rezult; var tempCollection = context.Get<Entity>(); // doing some stuff // последнее упоминание tempCollection в методе: var something = tempCollection.SomeProp; // doing some more stuff; return rezult; }
The local variable tempCollection
is mentioned only in the upper half of the method. Below this line, the code cannot access its content in any way. So GC quite rightly does not consider it to be the root in the lower half of the method.
Given this, adding an additional mention tempCollection
in the code (even if in the form of tempCollection = null
) does not shorten, but on the contrary, it will slightly prolong its lifetime.
It should be noted that when building in Debug, unlike Release, JIT takes care of your convenience and extends the tempCollection
area of life to the end of the scope (that is, to the end of the method). It does this solely for reasons of convenience when debugging - so that you can view the tempCollection
value even on the last line of the method.