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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s