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=http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet>

  <CodeSnippet Format=1.0.0>




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

      <Author>Microsoft Corporation</Author>









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



        <Literal Editable=false>




        <Literal Editable=false>





      <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);








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.

Comments (0)