This program prints "True" to console.
Allocate an object, make WeakReference of that, go to out of block scope, and check WeakReference.IsAlive.
public static void Main (string[] args)
{
Test ();
}
static void Test ()
{
WeakReference wref = null;
{ // block scope
var obj = new object ();
wref = new WeakReference (obj);
}
// obj is out of scope
// Console.WriteLine (obj);
GC.Collect ();
Console.WriteLine (wref.IsAlive); // => True
}
Why obj is not collected, though obj is out of scope?
The program is compiled by Mono 3.12.0.
EDIT:
Sorry, inappropriate example.
The following program also print True. Block scope seems be not related. This is tried not with Debug mode.
public static void Main (string[] args)
{
Test ();
}
static void Test ()
{
WeakReference wref = null;
var obj = new object ();
wref = new WeakReference (obj);
obj = null;
GC.Collect ();
Console.WriteLine (wref.IsAlive); // => True
}
$ mcs -debug- Program.cs
$ mono Program.exe