Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting/Removing event handlers in .Net

So I am stuck with fixing/maintaining another programmers code (blech)

I am a firm professor of the rule "If it ain't broke dont fix it!" so depsite wanting to change something every time I come across horrendous code, I am keeping myself limited to only changing the absolute minimum amount of code possible to make the required fixes. But in some cases I really need to understand something before trying to follow it/change it.

I came across this little bit here:

region.LineSelected = (x) => { };

And am wondering if it's the same as this:

region.LineSelected = null;

I want to be 100% positive of what the first line is doing before I go changing the method it's in.

like image 886
Neil N Avatar asked Dec 06 '22 06:12

Neil N


2 Answers

Edit based on my current opinion on the subject

They are not the same. The lambda version is adding an event handler to an empty anonymous method. This allows other code to freely raise LineSelected() without worrying about whether it is null (ie. having no listeners).

Eg.

var lineSelected = this.LineSelected;

if (lineSelected != null)
{
    lineSelected(EventArgs.Empty);
}

The above statement can throw a NullReferenceException if something unsubscribes from LineSelected in another thread after the if but before the event is raised. Assigning LineSelected to a temporary variable and then raising that can call an unsubscribed event listener. Assigning the event handler to a local variable is the recommended method of handling null delegates.

By adding an empty delegate, other code is always able to call LineSelected without fear of a NullReferenceException. By assigning the multicast event delegates to a local variable, you can be sure that the value cannot be modified by another thread.

like image 72
Richard Szalay Avatar answered Dec 07 '22 21:12

Richard Szalay


I can't think of any reason to have that first line of code. The only thing I can think of, is when raising the LineSelected event, if you have the first line of code in the class, you don't need to check if the LineSelected event is null. ie:

if (this.LineSelected != null)
{
   LineSelected(this,new EventArgs());
}

Instead, you can just raise the event without null checks.

However, with the second line of code, you will need to check for nulls.

like image 40
BFree Avatar answered Dec 07 '22 20:12

BFree