Broaden Your Event Horizons, part 2

Or, How I Learned To Stop Worrying And Raise An Event

In part 1 of our .NET Event adventure, we covered how enriching your events with custom arguments and availing an extensibility point will make all of your component’s consuming developer’s wildest dreams come true, and probably some of yours as well. Except for that one with the Unicorn. They’re not for real, dude, let it go.

As promised, here in part 2, I will lay out a code snippet to put some icing on the rich event cake. This will tighten up the tedium of declaring the handler delegate, the event-raising method, and the arguments class as well as the event itself. Without further ado, here is the content of the C# snippet:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets  xmlns="">
    <CodeSnippet Format="1.0.0">
            <Title>Declare An Event</Title>
            <Description>Snippet for generating a rich event</Description>
            <Author>Aptera Software</Author>
                <ToolTip>Replace with the event name.</ToolTip>
        <Code Language="csharp" Kind="method decl">
            <![CDATA[/// <summary>
    /// Raised when $EventName$.
    /// </summary>
    public event $EventName$Handler $EventName$;
    public delegate void $EventName$Handler(
            object sender, $EventName$EventArgs e);
    protected void On$EventName$($EventName$EventArgs e)
        if ($EventName$ != null)
            $EventName$(this, e);
    public class $EventName$EventArgs : System.EventArgs
        // TODO: add argument properties 

        /// <summary>
        /// Initializes the $EventName$EventArgs.
        /// </summary>
        public $EventName$EventArgs()
            // TODO: set argument properties

And here is a link to download both the VB and C# .snippet files (in a .zip file).

Installing the Snippet

If you have never installed a code snippet into Visual Studio before (or you have done, and just didn’t see committing the process to your long-term memory as “your thing”), here’s how:

  1. In Visual Studio, select Tools, Code Snippets Manager…
  2. On the Code Snippets Manager dialog, click the Import… button
  3. Select the .snippet file that you wish to install from its location on your file system
  4. On the Import Code Snippet dialog, check the location(s) to install the snippet (usually My Code Snippets will do)
  5. Click Finish

Using the Snippet

Now, in your component code, you should be able to just type “event”:

Hit the Tab key:

…and update the name of your shiny new event.

Also, I was just kidding about the Unicorn dream. ┬áRaising quality events is a very powerful technique, and anything is possible when you’re using .NET.