I think the if condition added for checking alive is culprit here the condition somehow does allow GC to collect weakreferences here.
below code should work for you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestWeakReference2
{
class Program
{
static void Main(string[] args)
{
Dog sb = new Dog("Bowser");
WeakReference _weak = new WeakReference(sb);
if (_weak.IsAlive)
{
Console.WriteLine((_weak.Target as Dog).ToString());
Console.WriteLine(_weak.IsAlive.ToString());
}
sb = null;
GC.Collect();
Console.WriteLine(_weak.IsAlive.ToString());
Console.WriteLine("[Done]");
Console.Read();
}
}
public class Dog
{
private string name;
public Dog() : this("noname")
{
}
public Dog(string name)
{
this.name = name;
}
}
}
removed the if condition to alive after GC.collect and it should be fine