#1,205 – C# 6.0 – Using the Null-Conditional when Invoking a Delegate
October 16, 2014 4 Comments
When you fire an event (by invoking a delegate), you typically need to check for null before invocation. This avoids a null reference exception if there are no subscribers to the event.
public class Dog { public Dog(string name, int age) { Name = name; Age = age; } public event EventHandler<string> NameChange; private string name; public string Name { get { return name; } set { if (value != name) { name = value; // Check for null before invocation if (NameChange != null) { NameChange(this, name); } } } } public int Age { get; set; } }
(The above pattern is not thread-safe).
An alternative pattern is to declare the event with a null handler, so that there is always at least one handler on the invocation list. (This is thread-safe).
In C# 6.0, we can use the null-conditional to invoke a delegate.
NameChange?.Invoke(this, name);
Is the new NameChange?.Invoke(this, name); thread safe?
I believe so
I’ll point out that a common pattern is to do
public event EventHandler NameChange = delegate {};
this always adds an empty delegate to the handler and therefore no null check is necessary
good idea on the empty delegate.