OdeToCode IC Logo

Snippets

Tuesday, December 6, 2005

Code snippets are a great productivity feature in Visual Studio 2005 (or a mind rot – depends on your perspective). Michael Palermo even has a site dedicated to code snippets: GotCodeSnippets.com.

Code snippets are easy to author. I became tired of typing in the same keystrokes to start a unit test, and wrote a snippet myself. Now I type tm+TAB+TAB, and voilà, the following code appears. A savings of 20 keystrokes:

[Test]
public void Test()
{

}

The word Test is highlighted in green as a replacement – I can type over the word with a new method name. All of this is setup by dropping the a .snippet file into My Documents\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets. Here are the contents:

<xml version="1.0" encoding="utf-8" ?>
<
CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
   <CodeSnippet Format="1.0.0">
      <Header>
         <Title>Test Method<Title>
         <
Shortcut>tm<Shortcut>
         <Description>Code snippet for a unit test<Description>
         <
Author>scott@OdeToCode.com<Author>
         <
SnippetTypes>
            <
SnippetType>Expansion<SnippetType>
            <
SnippetType>SurroundsWith<SnippetType>
         <SnippetTypes>
      <Header>
      <
Snippet>      
         <
Declarations>
            <
Literal>
               <
ID>nameID>
               <
ToolTip>Method name<ToolTip>
               <
Default>Test<Default>
            <Literal>
         <Declarations>
         <
Code Language="csharp">   
    public void $name$()
   {
      $selected$
   }
   
]]
         <Code>
      <Snippet>
   <CodeSnippet>
<CodeSnippets>

It looks like a lot of work, but if you copy an existing snippet it’s almost too easy.

Snippets are better in VB.NET. A code snippet in VB.NET can add Imports for required namespaces to the source file, and reference any required assemblies when it expands. C# cannot. Perhaps this explains why there are over 350 VB.NET code snippets installed by Visual Studio, and only 50 for C#. It would be great to write a TestFixture snippet for C# that automatically added a using NUnit.Framework, and added a project reference to the NUnit assembly. Perhaps in the next version…