Create safe events in C#

by Mads Kristensen 25. August 2006 00:36

Whenever you write class libraries, custom control or just about anything else, you probably raise a lot of home made events. That’s a simple thing to do, but tedious to write over and over again.

That’s why I always use this snippet for Visual Studio 2005 that writes the whole thing for me. Download the snippet and place it in the Visual Studio snippet folder which is placed at My documents\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets\.

Just fill out the name of the event and the EventArgs type that by default is EventArgs. It will then write the XML comment and a method that raises the event in a safe manor. That method is given the same name as the event, but prefixed “On”. So, if you create an event called Saved, the method that raises the event is called OnSaved.

This is what happens when you type evnt and hit TAB twice.

 

And after you’ve filled out the type of EventArgs and named the event Saved, this will be the result:

  public event EventHandler<EventArgs> Saved;

  /// <summary>

  /// Occurs when the class is Saved

  /// </summary>

  protected void OnSaved()

  {

    if (Saved != null)

    {

      Saved(this, new EventArgs());

    }

  }

This saves me for typing the same stuff over and over again.

For more snippets, visit Vault of Thoughts who has some nice ones.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

Server-side

Comments

9/27/2006 7:58:10 AM #

 Snippeteer

That's cool, but the OnXXX() method should be virtual.

Snippeteer |

8/13/2007 11:12:52 PM #

pingback

Pingback from mhinze.com

14 Links Today (2007-08-13)

mhinze.com |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008