Suppose there is a method inside the class:

public ICollection<Entity> GetData() { ICollection<Entity> rezult; var tempCollection = context.Get<Entity>(); //doing some stuff; return rezult; } 

Anyway, I need this temporary variable in the code. The question is whether this variable needs to be “zeroed out” ( tempCollection = null; ), so that the GC understands when garbage collection is no longer needed, or will it be clear, since it is declared inside the method?

  • one
    With C #, you don’t need to think about (practically) freeing memory. As soon as you no longer need the memory, it becomes available to the garbage collector. BUT: variable is not a memory at all! A variable is a place where a reference to the allocated memory can be put. The compiler allocates memory for a variable, and it generally can move it to a register, or to a stack, or move between these places, or duplicate, or not allocate at all, as it pleases. You can not affect the memory for variables (and should not try, the compiler does it better). - VladD

2 answers 2

When the method is completed, all its local variables disappear (unless they are captured by a closure). Separately, they do not need to be zoned.

  • four
    And sometimes they disappear before the completion of the method :) - ixSci

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.