Coding Horror

programming and human factors

Code Snippets in VS.NET 2005

One of the most enjoyable new features in Visual Studio .NET 2005 is Code Snippets. This animated GIF illustrates how it works:

VS.NET 2005 code snippets in action

I'm demonstrating three types of snippets here:

  • simple expansion
  • template expansion (with variables)
  • surround

The easiest way to enter a code snippet is to begin typing part of the snippet shortcut name, eg "prop" for property expansion. Once you've typed enough to uniquely select the snippet shortcut name, press:

Tab,Tab (in C#)

?,Tab (in VB.NET)

.. and the snippet will appear. If it's a templated snippet:

Tab advances to the next field

Shift+Tab moves to the previous field

Enter completes the snippet and resumes editing at your previous cursor position

If you want to enclose code in a surrounding snippet (eg, you have code highlighted for a region), you must manually invoke snippet intellisense by pressing:

Ctrl+K, Ctrl+X

VB.NET's implementation of snippets is a bit more robust than the one in C#.

  1. VB.NET has a zillion snippets shipping in the box where C# has maybe.. two dozen?
  2. VB.NET supports code snippets that automatically add any necessary Import statements.
The VB IDE team has a helpful code snippets FAQ that covers the language differences in detail.

There's a snippet management UI you can invoke via the Tools, Code Snippets Management menu, or by pressing:

Ctrl+K, Ctrl+B

From here you can import and export snippet files, but there's no editor for creating new ones. Snippets are just XML files with a ".snippet" extension that live in these language specific folders:

  • c:Program FilesMicrosoft Visual Studio 8VBSnippets1033
  • c:Program FilesMicrosoft Visual Studio 8VC#snippets1033
Assuming you don't enjoy editing raw XML files, it might be easier to go with Microsoft's Snippy, a GUI for creating VB.NET and C# code snippets. There's also Michael Palermo's new website for sharing code snippets, although there don't seem to be many there at the moment.

Written by Jeff Atwood

Indoor enthusiast. Co-founder of Stack Overflow and Discourse. Disclaimer: I have no idea what I'm talking about. Find me here: