Visual Studio Keyboard Tip #5 - Code Snippets

When I first saw code snippets in the Eclipse IDE a few years ago, I thought it was a great feature. It’s nice to see it included in Visual Studio 2005.

Let’s take a quick tour.

  1. Open up visual studio, and go to any C# code editor window.
  2. Position the cursor inside a method and enter CTRL + SPACE

Code Snippet Dropdown

In the dropdown that appears, look at the icon next to the #if or #region — that icon indicates the entry is a code snippet. Ok, next step:

  1. Type for
  2. This should set the selected index of the dropdown to the entry for.
  3. While for is selected enter TAB, then TAB again.

You should see this:

For Code Snippet

The caret is positioned on the i. Type the following word - index. Then hit TAB. You should see that all instances of i are replaced with index. Pretty cool.

Even better, all code snippets are defined in an xml format that you can edit.

  1. Enter the following keys CTRL + K, CTRL + B. This should bring up the code snippet manager.
  2. Expand the Visual C# node, then select for, in the location label right between the Language dropdown and the treeview gives you the location of the xml for the code snippet.
  3. Select and copy the path, then enter CTRL + 0 (that’s not a zero), and paste it into the filename, hit enter, and now you’ll see the xml for the code snippet.

This post on the VSEditor blog provides some details on the schema used to create a code snippet file.

I hope you are enjoying this series of visual studio keyboard tips. If you have any editor/keyboard topics that you would like to see, please feel free to comment on this blog and I’ll try and create a new post covering it. Thanks for reading!