I have a question concerning the GC in C#. According to this topic: C#: should object variables be assigned to null?
The garbage collector will collect a variable, when it is not used anymore in the code thereafter. However if I test it with the following code, the GC collector only collects the variable when it is set to null. (Commented out line) (If not set to null it is alive --> true, if it is set to null it is not alive --> false) What am I missing here?
Coffee coff = new Coffee();
coff.name = "test";
coff.number = 4;
WeakReference test = new WeakReference(coff);
//coff = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine(test.IsAlive.ToString());
Coffee class consists of the following:
public class Coffee
{
public string name { get; set; }
public string beans { get; set; }
public int number { get; set; }
}
@Edit 14:56 27-08-2014:
I found the answer inhttps://stackoverflow.com/questions/17130382/understanding-garbage-collection-in-net. It has to do with the following settings. I Qoute:
"You are being tripped up here and drawing very wrong conclusions because you are using a debugger. You'll need to run your code the way it runs on your user's machine. Switch to the Release build first with Build + Configuration manager, change the "Active solution configuration" combo in the upper left corner to "Release". Next, go into Tools + Options, Debugging, General and untick the "Suppress JIT optimization" option."