OdeToCode IC Logo


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:

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">
         <Title>Test Method<Title>
         <Description>Code snippet for a unit test<Description>
ToolTip>Method name<ToolTip>
Code Language="csharp">   
    public void $name$()

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…

Jason Kemp Tuesday, December 6, 2005
You can do the latter with Item Templates. The easy way is through the File -> Export Template... menu item. Not helpful if you want many fixtures per file, but if you do it once, you don't need to add the reference.
Keyvan Nayyeri Thursday, December 8, 2005
And this is my reason to love VB :D
I want to write some Snippets for my own use but can't find free time.
Fortunately Microsoft has given Snippet editor for VB so I would write a few lines of code ;)
Comments are closed.