#389 – Check for Null Before Raising an Event

You should always check to see if an event is null, before trying to raise it.

            if (Barked != null)
                Barked(this, new SomebodyBarkedEventArgs(Name, barkSound));

When no handlers are attached to the event, it will have a null value. If you try raising the event when it is null, you’ll get a NullReferenceException.

Alternatively, you could avoid having to check for null if you attach an empty handler to the event when you declare it.

        public event EventHandler<SomebodyBarkedEventArgs> Barked = delegate { };
Advertisement