C# Delegate Shortcut – No more null testing on events for subscribers
This is fairly well known but I realized I hadn’t seen it blogged about (sorry if already covered).
Your likely used to doing this:
public event EventHandler<AnimationImageEventArgs>
AnimationImageClicked;
private void OnClick(object sender, AnimationImageEventArgs e)
{
if (AnimationImageClicked != null)
AnimationImageClicked(sender, e); }
No need for that null check. I for one tend to forget them in the bowels of my teams code. What is better then eliminating the issue!
This is a way to ‘always have one subscriber’ which you can consider a sort of ‘null object’ pattern implementation for delegates. Checking for null just sucks and I love this kind of ubiquitous removal of it.
The first person I saw doing this was Juval Lowy, the master craftsman for basically all things .NET but known recently for utter mastery of WCF in his books and at his firm IDesign. Highly recommend all his writing, code samples and thoughts.
public event EventHandler<AnimationImageEventArgs>
AnimationImageClicked = delegate { };
private void OnClick(object sender, AnimationImageEventArgs e)
{
AnimationImageClicked(sender, e); }
Damon







Nice tips!
Thanks !