How is instance delegate method still accessible after the instance is set to null? The action delegate in the code below points to an instance method but the method is still available after the instance is set to null.
public class Work { public string Name{get;set;} }
public class Worker
{
public void Do(Work work)
{
Console.WriteLine("'{0}' is done.", work.Name);
}
}
public class BatchWorker
{
private List<Work> _works;
public readonly Action<Work> Worker;
public BatchWorker(Action<Work> worker)
{
_works = new List<Work>();
Worker = worker;
}
public void AddWork(Work work)
{
this._works.Add(work);
}
public void DoWorks()
{
this._works.ForEach(this.Worker);
}
}
public class Program{
public static void Main(){
var worker = new Worker();
var batchWorker = new BatchWorker(worker.Do);
batchWorker.AddWork(new Work {Name = "Task 1"});
worker = null; // the instance is now null.
Console.WriteLine("Target worker is null? {0}\r\n", batchWorker.Worker.Target == null);
// How is this having access to instane method after the instance is null?
batchWorker.DoWorks();
}
}
OUTPUT
Target worker is null? False
'Task 1' is done.