Code snippets are a great time saver and they are pretty simple to create.  Any time you find yourself typing the same thing over and over again, you may want to consider creating your own code snippet to make life easier.

Here’s an example… I was recently working on a large refactor of some error handling code for a user interface.  Basically, I went from form to form, refactoring the way the error handling was implemented and then test it.  How did I test it?  By throwing exceptions in my code.  Doing so is pretty easy, just find the portion of code that needs to be tested and type “throw new Exception(“This is a test”);”  Plus, for good measure and safety I’d add this above it: “//TODO – Don’t forget remove this test code”

//TODO:  Don't forget to remove this test code:
throw new Exception("This is a test");

Sure, it is easy enough to type but it got old pretty quick and I decided to create a simple snippet.  Once I did, all I needed to type was “tne” (it stands for “Throw New Exception) and hit “tab” twice (hitting “Tab” twice tells Visual Studio to use the code snippet based on what you just typed).  Sounds cool huh?  Ok so here is how you create a simple code snippet…

Snippets are stored in XML files on your pc.  To create a new one, it is easiest to just start with an existing snippet and modify the xml to meet your needs.  Here is an example of the one I am using:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Throw new Exception</Title>
      <Shortcut>tne</Shortcut>
      <Description>This will generate code to throw a new Exception</Description>
      <Author>Andy Schwam</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Code Language="csharp">
        <![CDATA[    //TODO: Remove this test code:
        throw new Exception("An Exception has been thrown"); $end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

If you want to use your own snippet, just change the Title, Shortcut, Description and Author elements.  And of course, you need to put your snippet inside of the CDATA area of the the Code Element.

Next, you just need to save this file in a place where Visual Studio will pick it up.  To tell VS2008 where to look for it, go to Tools > Code Snippets Manager.  Make sure you select the correct language in the drop down, otherwise Visual Studio can’t connect your snippet to the language you meant it for.  You’ll also notice the existing folders for snippets.  That may give you an idea of where you should store your own snippets ;).

You can also write more complex snippets that allows you to use the snippet and then type in values that get used within the snippet.  For instance, I do a lot of work with Silverlight and for databinding my public variables must implement INotifyPropertyChanged.  Instead of manually typing a property that does so, plus a backing variable, I use a snippet with the shortcut “npc”.  In the sample below, you will see the words TYPE, PROPERTY and FIELD highlighted in Green.  Those are placeholders and when I utilize the code snippet, VS will prompt me to replace those values.  So if I want to create a public property and backing variable for a string FirstName, I just type the following:  “npc” TAB TAB “string” TAB “FirstName” TAB “_firstName” (but don’t type the quotes!).  It may seem weird at first but makes coding much easier.

private TYPE FIELD; 

image

Here is the XML for my “NotifyPropertyChanged” snippet:

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

<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Notify Property Changed Property</Title>
      <Shortcut>npc</Shortcut>
      <Description>Code snippet for creating a property with a backing variable that calls NotifyPropertyChanged</Description>
      <Author>Andy Schwam</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>type</ID>
          <ToolTip>The Type for the Property</ToolTip>
          <Default>TYPE</Default>
        </Literal>
    <Literal>
          <ID>fieldname</ID>
          <ToolTip>The Type for the field</ToolTip>
          <Default>FIELD</Default>
        </Literal>
    <Literal>
          <ID>propertyname</ID>
          <ToolTip>Parameter name</ToolTip>
          <Default>PROPERTY</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
    public $type$ $propertyname$ {
    get { return $fieldname$; } 
    set 
    { 
    if ($fieldname$ != value) 
    { $fieldname$ = value; 
    NotifyPropertyChanged("$propertyname$");
    }
    }
    }
    private $type$ $fieldname$; 
    $end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Unfortunately, there isn’t a Code Snippet Editor included in VS.  There is some kind of plug-in available for creating VB snippets but I’ve never used it.  I’m sure you can find it with your favorite search engine.  Still it is pretty easy to write these yourself.

Leave a reply

required

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>