Write your own Visual Studio .NET Snippets to improve your coding productivity

Chances are that if you’ve been using Visual Studio .NET, you’ll have come across the concept of snippets – useful reusable chunks of code that are inserted after typing in a small textual identifier for that snippet. This tutorial describes Visual Studio .NET snippets and describes how you can create your own.

A snippet that I use probably the most is the ‘prop’ snippet. To activate it, type ‘prop’ at class scope in a Visual C# project.

The ‘prop’ snippet for quickly inserting a property at class scope

Selecting ‘prop’ from the list, or tabbing twice will then produce the following code:

The initial code produced by the ‘prop’ snippet

The focus is initially over the private member’s data type ‘int’. This, and all the other text highlighted in green can be typed over. Each piece of text can be cycled through by pressing the tab key.

You’ll also notice that the property’s type is outlined with a dotted line. This means that once something has been typed in the active selection, tabbing out will change the dotted selection’s text to be the same. This makes sense, since a property and the member that it relates to must be the same type.

In this quick scenario, we’ll change the data type to be of type string, the member to be _name, and property to be Name. Note that tabbing through will cycle through the highlighted text. When you’re happy, press enter, and you have a property. Once the method for using snippets becomes familiar, their use becomes second nature and you’ll wonder how you ever worked without them.

The ‘prop’ example is just one of many that can be managed through the ‘Code Snippets Manager’, accessed from the Visual Studio Tools menu.

The code snippets manager

The real fun with snippets (real fun? perhaps I need to get out more) comes with developing your own. The rest of the tutorial will create a simple property snippet to write/read information to/from the ViewState on an ASP.NET page.

A snippet is just an XML file, and the default Visual Studio snippets can be found in C:Program FilesMicrosoft Visual Studio 8VC#Snippets1033Visual C# by default.

The default Visual Studio snippets folder

If we open the prop.snippet file, we get this:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>prop</Title>
      <Shortcut>prop</Shortcut>
      <Description>Code snippet for property and backing field</Description>
      <Author>Microsoft Corporation</Author>
      <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
   </Header>
   <Snippet>
     <Declarations>
        <Literal>
          <ID>type</ID>
          <ToolTip>Property type</ToolTip>
          <Default>int</Default>
        </Literal>
        <Literal>
          <ID>property</ID>
          <ToolTip>Property name</ToolTip>
          <Default>MyProperty</Default>
        </Literal>
        <Literal>
          <ID>field</ID>
          <ToolTip>The variable backing this property</ToolTip>
          <Default>myVar</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[private $type$ $field$;
	public $type$ $property$
	{
          get { return $field$;}
          set { $field$ = value;}
	}
	$end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

The two main areas are the Header and the Snippet elements, underneath the main CodeSnippet element. The Header contains the snippet title, shortcut (what you type in the editor to invoke the snippet), the description, author, and the snippet types. In our case, it’ll be an Expansion type, meaning it will expand to generate a piece of code.

The Snippet element contains a declarations section. This section contains 0 or more (in this case 3) items, 1 for each item that can be customised. Each of these items has a unique identifier, ID, a tooltip and a default value. The Snippet element also contains a Code section. Wrapped in a CDATA section (since it’s quite likely we’ll be using reserved xml characters in here), it contains the injected code. The variables declared in the Declarations are referenced in $s. The $end$ defines where the cursor will be when the user types enter.

When I develop my own snippets, I often find it useful to start with an example of the type of code that the snippet will produce, before developing the snippet and removing ‘configurable’ items.

public string SelectedValue
{
  get { return ViewState["SelectedValue"] == null ? 15 : (int)ViewState["SelectedValue"]; }
  set { ViewState["SelectedValue"] = value; }
}

So, thinking about a snippet, it would be good to define the type of the property (string), the property name (SelectedValue), which is also used as the ViewStateIdentifier, and the default value (15).

Translating that into the snippet code gives us:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>propvs</Title>
      <Shortcut>propvs</Shortcut>
      <Description>Code snippet for property and ViewState backing</Description>
      <Author>Shane Porter</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>type</ID>
          <ToolTip>Property type</ToolTip>
          <Default>string</Default>
        </Literal>
        <Literal>
          <ID>property</ID>
          <ToolTip>Property name</ToolTip>
          <Default>MyProperty</Default>
        </Literal>
        <Literal>
          <ID>default</ID>
          <ToolTip>The default value, if the ViewState value is null</ToolTip>
          <Default>string.Empty</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[public $type$ $property$
        {
          get { return ViewState["$property$"] == null ? $default$ : (int)ViewState["$property$"]; }
          set { ViewState["$property$"] = value; }
        }
	$end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Things are pretty simple. I took the code that I wanted, thought about what I needed, created a variable (Literal element) for each thing, and replaced the hard-coded values in the pasted C# code to the $variable$ syntax. I called the snippet ‘propvs’, since it uses the View State, and doesn’t clash with the default ‘prop’ snippet. You can have multiple snippets with the same name, but it becomes a little harder to distinguish them at usage-time since the Visual Studio IDE simply presents the two in a menu.

To use the snippet, you’ll need to import it using the Visual Studio Tools -> Code Snippets Manager menu item. On the resulting dialog, click the ‘Import’ button and browse for the snippet. You will then see this dialog:

Importing the snippet

Once Finish is clicked, click OK on the previous dialog to return to the editor. Then, we can use our newly developed snippet by typing propvs and tabbing, or by selecting from the menu.

Selecting ‘propvs’ from the intellisense menu

Once this has been selected, you will get the injected code:

The ‘propvs’ injected code

Tabbing through, typing what we need, will give us a very quick and easy way to insert the viewstate property pattern into our code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.