Submit Your Site For Free!

Email Address:
* URL:
*
*Indicates Mandatory Field

Terms & Conditions

CProgramTrends
FlashNewz
DevWebPro








Creating Safe Events In C#

By Mads Kristensen
Expert Author
Article Date: 2006-11-01

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 documentsVisual Studio 2005Code SnippetsVisual 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 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.

Comments

Add to Del.icio.us | Digg | Reddit | Furl

Bookmark WebProNews:

About the Author:
Mads Kristensen currently works as a Senior Developer at Traceworks located in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in 2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and web services in his daily work as well. A true .NET developer with great passion for the simple solution.

http://www.madskristensen.dk/



Newsletter Archive | Article Archive | Submit Article | Advertising Information | About Us | Contact

C Programming Trends is an iEntry, Inc. ® publication - 1998-2008 All Rights Reserved Privacy Policy and Legal