BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Visual Studio
VS 2005+

Creating Visual Studio Code Snippets

Visual Studio 2005 introduced the code snippet feature, which allows boilerplate code to be quickly inserted into a source code file. A number of standard snippets are provided. These may be enhanced with the creation of custom code snippets.

Code Snippets

Code snippets were introduced in Visual Studio 2005. They are small sections of commonly used code that can be quickly inserted into your source code. This can save time spent typing and increase your productivity. Snippets may be inserted at the cursor position or surrounding a selected piece of code. They may include placeholders for variables, parameters or other elements that you can tab between to enter desired values.

When you install Visual Studio some code snippets are immediately available. These include snippets that generate looping structures, define properties and create the boilerplate code for exception types. You can also create your own code snippets containing all of the features of the standard items.

In this article we will create and register a basic code snippet that inserts the code for the basic IDisposable pattern. This will not include advanced snippet features such as placeholders, which will be explained in a future article.

Creating a Code Snippet

Code snippets are XML files that contain the code that to be inserted, elements that control its behaviour and metadata such as the author's name. These files are created using Visual Studio's XML editor, or an alternative text editor, and are saved with the ".snippet" extension. They may then be registered using the Code Snippets Manager.

Creating the Snippet

We will begin by creating the code snippet XML file. Start Visual Studio and create a new XML file by opening the File menu and selecting "New" and "File...". When prompted for the type of file to create, choose "XML File". The new file should contain a default xml element only.

The root element for a code snippet has the name, "CodeSnippet". To enable Visual Studio to validate the XML and to provide Intellisense support for code snippets, you can also define the format for the snippet and the XML namespace to use. To do so, add the element shown below:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippet Format="1.0.0"
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">

</CodeSnippet>

Adding Header Details

The Header element defines metadata for the code snippet. We will add five child elements:

  • Title. The name for the code snippet. This name appears in the Intellisense for the code snippet and within the Code Snippets Manager when registering it.
  • Author. The name of the individual or company that created the code snippet.
  • Shortcut. The text that the developer will type in order to insert the code snippet. For the sample snippet the developer will type "idisp" before pressing the tab key twice.
  • Description. A description of the snippet, which is visible in Intellisense.
  • SnippetTypes. This element controls the behaviour of the inserted snippet. Snippet types will be described in a future article.

To add this metadata, add the following XML within the CodeSnippets element:

<Header>
    <Title>Simple IDisposable Code Snippet</Title>
    <Author>BlackWasp</Author>
    <Shortcut>idisp</Shortcut>
    <Description>Code for the basic IDisposable pattern.</Description>
    <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
</Header>

Adding the Code

The next step is to add the code to insert when the snippet is used. This is held in the contents of the Snippet element, which is a child of the CodeSnippet root. To specify the language for the snippet you must add the Language attribute. The available options are CSharp, VB, VJSharp and XML. We will use CSharp.

The snippet code is usually held in a CDATA section within the Snippet element. This allows you to use symbols such as <, > and &, which would otherwise cause problems with the XML structure or would need to be converted to escaped sequences.

The sample snippet contains the code required within a class that implements the IDisposable interface with no finalizer. Add the following within the CodeSnippet element to complete the snippet's XML.

<Snippet>
    <Code Language="CSharp"><![CDATA[private bool _disposed;

public void SampleMethod()
{
    if (_disposed) throw new ObjectDisposedException("MyObject");
}

protected virtual void Dispose(bool disposing)
{
    if (!_disposed)
    {
        if (disposing)
        {
            // Dispose managed resources
        }

        // Dispose unmanaged resources
        _disposed = true;
    }
}

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}]]>
    </Code>
</Snippet>

You can now save the snippet using the file name, "IDisposable.snippet".

21 February 2011