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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With