This is an interesting one. Jeffrey Richter talsk a lot about this in CLR via C#.
With a null check like the following:-
var handler = MyEvent;
if (handler != null)
{
handler.Invoke(null, e);
}
The JIT compiler could potentially optimise away the handler
variable entirely. However, the CLR team are aware that many developers use this pattern for raising events and have built this awareness into the JIT compiler. It is likely that this will remain in place in all future versions of the CLR because changing the behaviour might break too many existing applications.
There is no reason that you can't write an extension method to do this work for you (this is exactly what I have done). Note that the method itself may be JIT inlined (but the temporary variable still won't be optimised away).
If you envisage your application being used against another runtime, e.g. Mono (which I suspect mirrors the CLR's behaviour in this case anyway) or some other exotic runtime which may appear, then you can guard your code against the possibility of JIT inlining by adding [MethodImplAttribute(MethodImplOptions.NoInlining)]
to your extension method.
If you decide not to use an extension method, another way to protect against JIT optimisation (which Jeffrey Richter recommends) is to assign the value to the temporary variable in a way which cannot be optimised away by the JIT compiler, e.g.
var handler = Interlocked.CompareExchange(ref MyEvent, null, null);