Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I thought I understood delegates, but I clearly don't since this code gives me output different than I was expecting. Why doesn't the invoke throw a NullRefenceException after we assign speaker to null or to a new instance? Is it because the garbage collector has not had a chance to clean things up?

What I have tried:

C#
void Main()
{
	var speaker = new Speaker();
	Action action = new Action(speaker.SayName);
	
	speaker.Name = "Luke";
	action.Invoke(); // outputs "My name is Luke"
	
	speaker.Name = "Leia";
	action.Invoke(); // outputs "My name is Leia"
	
	speaker = null;
	action.Invoke(); // outputs "My name is Leia"
	
	speaker = new Speaker();
	speaker.Name = "Chewy";
	action.Invoke(); // outputs "My name is Leia"
}


class Speaker
{
	public string Name { get; set; }
	
	public void SayName()
	{
		Console.WriteLine($"My name is {Name}");
	}
}
Posted
Updated 4-Sep-20 2:53am

1 solution

C#
// this creates a Speaker object in memory (let's say at address 10000)
// and creates a speaker variable that references that object (at address 10000)
var speaker = new Speaker();
// This creates an Action with a target that is the SayName method on the object
// at memory address 10000
Action action = new Action(speaker.SayName);

// ...

// this stops speaker pointing to memory address 10000 but the
// object at 10000 (the Speaker object) still exists, so the SayName
// method that Action is referencing also still exists
speaker = null;
// this does what it always has done, calls SayName on the object at address 10000
action.Invoke(); // outputs "My name is Leia"

// setting a variable to null only destroys that object (during GC) if nothing else
// is referencing that object.  However as the Action is referencing the
// object at address 10000 it is not destroyed.
 
Share this answer
 
v2
Comments
Sandeep Mewara 4-Sep-20 8:55am    
5!
Sandeep Mewara 4-Sep-20 8:56am    
Additionally, "Is it because the garbage collector has not had a chance to clean things up?"
This address will not be cleaned as it is still being referenced by Action.
F-ES Sitecore 4-Sep-20 9:57am    
GC will never clean it up as it has an active reference. Until the Action object no longer exists anyway.
CPallini 4-Sep-20 9:22am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900