The OnXYZ method should always follow this form:
public void OnXYZ() { var evt = XYZ; if (evt != null) evt(sender, e);
There are several reasons for this form:
- Checking
if evt != null ensures that we will not try to call the null delegate. This can happen if no one has connected an event handler to the event. - In a multi-threaded scenario, since the delegates are immutable, as soon as we get a local copy of the delegate in
evt , we can safely call it after checking for a non-zero value, because after but before the call.
What to pass for e is different if you need to pass a child of EventArgs with a parameter, there are two ways:
public void OnXYZ(string p) { var evt = XYZ; if (evt != null) evt(sender, new SomeEventArgs(p)); }
or more often it is:
public void OnXYZ(SomeEventArgs e) { var evt = XYZ; if (evt != null) evt(sender, e); }
This syntax is:
evt(sender, e);
is just another way to write this:
evt.Invoke(sender, e);
Also note that the event is an event from outside your class, only add or remove event handlers can be processed from it.
Inside your class, an event is a delegate, you can call it, check the target or method, view the list of subscribers, etc.
In addition, a new ?. Operator is introduced in C # 6 ?. - Null-conditional operator - which is mostly not suitable for if not-null, dereference , which may shorten this method:
public void OnXYZ(SomeEventArgs e) { var evt = XYZ; if (evt != null) evt(sender, e); }
in it:
public void OnXYZ(SomeEventArgs e) { XYZ?.Invoke(sender, e); }
which can be further abbreviated using elements expressed by:
public void OnXYZ(SomeEventArgs e) => XYZ?.Invoke(sender, e);
Please note that this is not possible to write:
XYZ?.(sender, e);
therefore, in this case, you must use Invoke yourself.