From this question (and others) there’s this example of snapshoting the event handler value before invoking:
var tmp = _myEventHandler;
if(tmp != null) {
tmp(sender, args);
}
However, if I pass in the event handler and args into a function does this do the same thing?
protected void Invoke(MyEventHandler handler, MyEventArgs args)
{
if (handler != null)
handler(this, args);
}
I would say yes, but after thinking about this I don’t know if it is the same – like could an optimization process inline this function and remove the snapshot variable?
It indeed does the same thing. The code is simply checking that the event handler is non-null and hence available for raising. This code is no different for a field / parameter / local. The C# compiler or JITer cannot inline this in such a way that the temporary is removed because it would change the semantics of the program.