Code Snippets in Visual Studio 2010

Visual Studio allows developers to save snippets of code which can be inserted at a later time. This saves on retyping blocks of code that are used often. I also find it very useful when I have to show code during presentations. Instead of typing everything live, I find it far easier to simply add the code block by block using code snippets.

VS 2010 improves the snippet functionality, and makes it easier to create code snippets. There’s two types of snippets:

- Expansion snippets are inserted at the cursor
- SurroundsWith snippets wraps around selected code

 

Creating a Custom Snippet:
Let’s go ahead and create a try-catch-finally Expansion snippet:

- Insert a new XML file to the project and call it TryCatchFinally.snippet. Make sure the file name ends with .snippet

- Right-click on the editor window and select Insert Snippet->Snippet. This creates a basic XML snippet template as shown below:

<CodeSnippet Format="1.0.0" 
             xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>title</Title>
    <Author>author</Author>
    <Shortcut>shortcut</Shortcut>
    <Description>description</Description>
    <SnippetTypes>
      <SnippetType>SurroundsWith</SnippetType>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>name</ID>
        <Default>value</Default>
      </Literal>
    </Declarations>
    <Code Language="XML">
      <![CDATA[<test>
      <name>$name$</name>
      $selected$ $end$</test>]]>
    </Code>
  </Snippet>
</CodeSnippet>

- As you can see, by default the template contains both snippet types. Since I am creating an Expansion snippet, let's go ahead and get rid of the <SnippetType>SurroundsWith</SnippetType> tag.

- Update the Title to "Try Catch Finally", Shortcut to "trycf" and Description to "Adds a try-catch-finally block".

- Literal tag enables us to define editable values that are inserted into the snippet. In the try-catch-finally snippet, we want to allow the user to change the type of the Exception being caught. The ID tag is the name of the editable value so change it to "ExceptionName". The Default tag specifies the default value for our editable field. I want to catch all exceptions, so change the Default tag's value to "Exception".

- Finally, the code section contains what will be added when the snippet is inserted. Change the language to "CSharp", and the body to the following:

    <Code Language="CSharp">
      <![CDATA[
try
{

}
catch($ExceptionName$)
{

}
finally
{

}
      ]]>
    </Code>

- The final version of the TryCatchFinally.snippet file is shown below. For more details about the XML schema, take a look at the MSDN code snippets Schema Reference

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" 
             xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>Try Catch Finally</Title>
    <Author>umair</Author>
    <Shortcut>trycf</Shortcut>
    <Description>Adds a try-catch-finally block</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>ExceptionName</ID>
        <Default>Exception</Default>
      </Literal>
    </Declarations>
    <Code Language="CSharp">
      <![CDATA[
try
{

}
catch($ExceptionName$)
{

}
finally
{

}
      ]]>
    </Code>
  </Snippet>
</CodeSnippet>

Loading the Snippet into Visual Studio:

There are two ways to insert the above snippet into Visual Studio.

The most straightforward way is to put the .snippet files in VS 2010's code snippets directory. The default location for it is C:\Users\<UserName>\Documents\Visual Studio 2010\Code Snippets\. This folder contains sub-directories based on the language of the snippet. For my example, the snippet goes under Visual C#. Once put here, VS 2010 automatically picks up the snippets without the need to restart.

 

The second option is to import the .snippet file into Visual Studio.

- Inside Visual studio, go to Tools->Code Snippets Manager (Ctrl+K,Ctrl+B). This brings up the Snippets Manager.

- Press Import button, and navigate to the location where the snippet was saved. Select the .snippet file.

- Press OK.

 

Using the Code Snippet:

Type the name of the snippet (the shortcut), and pressing tab expands it.

Intellisense after typing snippet name

You can also press Ctrl+K and Ctrl+X which brings up the "Insert Snippet" menu as shown below:

We can navigate to My Code Snippets, and select the TryCatchFinally that we've just added:

About these ads

7 Comments

Filed under Visual Studio

7 responses to “Code Snippets in Visual Studio 2010

  1. Pingback: 2010 in review | Umair's Blog

  2. Mir

    Just wondering, is the code snippet in vs2010 the same as the bundle editor in text-mate as far as the functionality is concerned.

    • Umair

      I don’t have a lot of experience with Textmate, and haven’t used its bundle-editor. From what little I know, bundles for Textmate are very general and provide a lot of power in how you want to customize your editor. As I understand, you can definitely use bundles to create & insert code snippets in Textmate. Here’s a link on how to do that:

      http://www.snippetsapp.com/blog/snippets-bundle-for-textmate.html

      • Mir

        Is there something like the bundle in visual studio 2010, meaning can i create my own snippets of code and bring then in with short-cut key like Textmate.(i’m new to visual studio).
        Thanks.

  3. Mir

    read the tutorial above, got everything i needed. Guess i should have read the tutorial completely before posting the comment.
    Really helpful thanks :)

  4. Pingback: Фрагменты кода в Visual Studio 2010 (Snippet) | Программирование на C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s