TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C# Coding Standard
Search

Rule:  9@113Checked automatically with code checker

Synopsis:Always check an event handler delegate for null
Language:C#
Severity Level:1
Category:Delegates and events


Description:

An event that has no subscribers is null, so before invoking, always make sure that the delegate list represented by the event variable is not null. Furthermore, to prevent conflicting changes from concurrent threads, use a temporary variable to prevent concurrent changes to the delegate.

Wrong example:

  event EventHandler Notify;
  void RaiseNotifyEvent(NotifyEventArgs args) 
  {
      EventHandler handlers = Notify; 
      handlers(this, args);
  }

Correct example:

  event EventHandler Notify;
  void RaiseNotifyEvent(NotifyEventArgs args) 
  {
      EventHandler handlers = Notify; 
      if (handlers != null) 
      { 
          handlers(this, args);
      }
  }

Tip You can prevent the delegate list from being empty altogether. Simply assign an empty delegate like this:

  event EventHandler Notify = delegate {};



Literature References:
Aviva AV1220