1

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.

implmentor
  • 1,386
  • 4
  • 21
  • 32
Biniam Eyakem
  • 545
  • 5
  • 18

2 Answers2

5

Your misunderstanding lies here:

// the instance is now null.

It's not. You just changed the variable worker to point to null. That does not somehow destroy or nullify the instance of Worker.

Maybe reading up on what variables, objects and references are would help. There was a question exactly about that not long ago: What is the difference between a variable, object, and reference?

Community
  • 1
  • 1
germi
  • 4,628
  • 1
  • 21
  • 38
3

A delegate contains a reference to the instance that it is to be called on. The line:

var batchWorker = new BatchWorker(worker.Do);

Creates a second reference to worker that is stored in Worker action in BatchWorker. Because there is still an active reference to the worker instance it will not be garbage collected.

shf301
  • 31,086
  • 2
  • 52
  • 86