Reputation: 1455
I've seen some coders on pluralsight cast their EventHandler to a delegate before executing. Why is this a good practice? Usually I just invoke the event without casting.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication13
{
public class Mediator
{
public event EventHandler<EmployeeArgs> EmployeeEventChange;
private static readonly Mediator _Instance = new Mediator();
private Mediator() { }
public static Mediator GetInstance()
{
return _Instance;
}
public void OnEmployeeHandler(Employee e)
{
var EmployeeEventDelegate = EmployeeEventChange as EventHandler<EmployeeArgs>;
if (EmployeeEventDelegate != null)
{
EmployeeEventDelegate(this, new EmployeeArgs()
{
Employee = e
});
}
}
}
}
Upvotes: 2
Views: 243
Reputation: 125610
The cast is (imo) pointless, but the fact that it's being assigned to local variable has a value - it makes the invocation thread safe. You can ready more about it here.
If you didn't assign your event handler to local variable and someone unsubscribed the last delegate from it between != null
check and invocation, you'd get an exception. By making a copy you are sure that nobody changes the list of subscribers you know about between null
check and invocation.
Upvotes: 2