VS 2005 code snippet for a typical event

If you follow the guidelines, events have a decent chunk of boilerplate code - they'll typically have an associated EventArgs subclass (typically with an Empty property), they'll have the event declaration, and then they'll have the OnEvent method to raise the event.

Since it's boilerplate (in many cases, certainly not all), it's ripe for a VS 2005 snippet - I shoved this into my Visual Studio 2005\Code Snippets\VC#\My Code Snippets directory as event.snippet - no VS restart was needed - I dropped it in and my running VS started working with the snippet immediately.  Edits to the snippet were similarly immediate, which was very nice while I was making modifications to the snippet.

Note that this snippet is intentionally simple - changing things like the public modifiers to their own literals is definitely possible, but I'm trying to KISS for the hopeful goal of easier human-parsing, since I want people making all kinds of useful snippets out there.

<?xml version="1.0" encoding="utf-8" ?>

<CodeSnippets xmlns="https://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">

<CodeSnippet Format="1.0.0">

<Header>

<Title>event</Title>

<Shortcut>event</Shortcut>

<Description>Code snippet for event declaration, EventArgs subclass, and method for raising it</Description>

<Author>Microsoft Corporation</Author>

<SnippetTypes>

<SnippetType>Expansion</SnippetType>

</SnippetTypes>

</Header>

<Snippet>

<Declarations>

<Literal>

<ID>eventname</ID>

<ToolTip>Event name, either NounVerbing or Verbing for pre-events, or NounVerbed or Verbed for post-events</ToolTip>

<Default>NounVerbed</Default>

</Literal>

<Literal Editable="false">

<ID>eventargs</ID>

<Function>SimpleTypeName(global::System.EventArgs)</Function>

</Literal>

<Literal Editable="false">

<ID>eventhandler</ID>

<Function>SimpleTypeName(global::System.EventHandler)</Function>

</Literal>

</Declarations>

<Code Language="csharp">

<![CDATA[public class $eventname$EventArgs : $eventargs$

{

public static readonly new $eventname$EventArgs Empty = new $eventname$EventArgs();$end$

}

public event $eventhandler$<$eventname$EventArgs> $eventname$;

protected virtual void On$eventname$($eventname$EventArgs e)

{

$eventhandler$<$eventname$EventArgs> handler = $eventname$;

if (handler != null)

{

handler(this, e);

}

}]]>

</Code>

</Snippet>

</CodeSnippet>

</CodeSnippets>

 

Now when I need a new event, I can just type "event", hit TAB, then fill in the name of the event.  Dig around in your Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C# directory for lots of nice ones that come built-in and get ideas for new ones as well!  Also, if you're using Visual Studio Team System, make sure to check out the code snippets that Jim Newkirk uploaded onto GotDotNet.