Following on from my recent post about code snippets for property declarations, I thought I’d share the snippet I use for event declarations.
Original posted April 2008, updated May 2009 with a revised version of the snippet.
There are three well motivated conventions in the .NET community around events and how you implement them.
-
Use the event keyword to declare the outward facing event as a proper event block - this tells the compiler to enforce event conventions, preventing outside code from doing anything untoward.
-
Use protected method named OnXXX to trigger the event when required. This method should check that we have at least one event subscriber, and should create an appropriate EventArgs instance for the event. Any parameters required by the arguments object should be passed to the OnXXX method.
-
To avoid possible multithreading issues and null reference exceptions, the OnXXX method should cache the event handler in a local variable before checking for null and calling any registered handlers.
These conventions mean that any event declaration requires at least three parts - the event itself, a member variable for storage, and a triggering method for calling.
I’ve wrapped these up in a simple code snippet called event, which expands as follows:
There are five parameter fields to complete in this snippet. In order they are:
- The name of the event;
- The type of the event handler;
- Parameters required by the OnXXX() method;
- The type of the event arguments object to pass;
- Parameters required by the constructor of the event arguments object.
Most snippets have just one or two fields, making this one more complex than most. Hopefully an example will make things clear. Declaring a PropertyChanged event (as required by the INotifyPropertyChanged interface) requires:
- In the code editor, ‘event’; press Tab.
- Enter ‘PropertyChanged’ as the name of the event; press Tab.
- Enter ‘PropertyChangedEventHandler’ as the type of the handler; press Tab.
- Enter ‘string property’ as the arguments to OnPropertyChanged(); press Tab.
- Enter ‘PropertyChangedEventArgs’ as the type of the EventArgs to pass; press Tab.
- Enter ‘property’ as the parameter for the constructor of the PropertyChangedEventArgs; press Enter;
Phew!
You certainly have to know exactly what you want before you trigger this snippet. That said, the snippet allows you to focus on what you’re doing by providing the code required to meet the usual conventions without distraction.
If you want to use the event snippet yourself, download the zip file.
See Also
To read more about why you need to use a local variable to make the event handler threadsafe, see Brad Abrams blog post Design Guidelines, Managed code and the .NET Framework at http://blogs.msdn.com/brada/archive/2005/01/14/353132.aspx
Comments
blog comments powered by Disqus