Raising Events in C#

Raising events in VB.NET is easy, not so much in C# since you have to check for “listeners” manually. Using the Raise Extension method (listed below), it’s now as easy as VB.NET and it’s thread safe.

public static class EventExtensions
   /// <summary>
   /// Raises the specified handler.
   /// </summary>
   /// <typeparam name="TEventArgs">The type of the event args.</typeparam>
   /// <param name="handler">The handler.</param>
   /// <param name="sender">The sender.</param>
   /// <param name="e">The <see cref="TEventArgs"/> instance containing the 
   ///                 event data.</param>
   public static void Raise<TEventArgs>(this EventHandler<TEventArgs> handler, 
                        object sender, TEventArgs e) where TEventArgs : EventArgs
      EventHandler<TEventArgs> copy = handler;
      if (copy != null)
         copy(sender, e);

Below is an example on how to use it:

public event EventHandler<EventArgs> ScheduledEventDeleted;
ScheduledEventDeleted.Raise<EventArgs>(this, null);

Tip By: David McCarter