Visual Studio Snippets

You may not know what snippets are in Visual Studio, but I am very confident that you have used them before. Let me explain a way to add custom snippets to Visual Studio which will speed up your development time for menial code blocks.

Probably, the most commonly used snippets are those which appear for Visual Studio keywords. Things like creating properties, foreach loops etc. Go ahead and try it. Open a blank C# document and type foreach, then press the TAB key. See what happened? Visual Studio did the hard work for you and added all the code required for the block you wanted. It even did it in a best practice syntax and style.

foreach snippet expanded

You can create your own snippets like this.

One of my favourites is the list of Bootstrap classes that are used for responsive design. The end product is this

<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"></div>

And I would use this for almost every HTML element on my page. So I created a snippet that handles this for me. I use the shortcut text of bsclass, which I type then press TAB. The snippet inserts the entire class attribute and values into the document at the position of the cursor. That has to save me at least a minute on each HTML element.

Here is how you do it.

The snippet file is an XML document. Open Notepad and copy/paste the below text (you will have to make some edits for your own snippet text.

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="">
  <CodeSnippet Format="1.0.0">
      <Title>Bootstrap Responsive Classes</Title>
      <Code Language="html"><![CDATA[class="col-xs-12 col-sm-12 col-md-12 col-lg-12"]]><\Code>

Now go and change the text in these sections

  • Title – just a title for the snippet. This will be displayed if you insert the snippet via the Edit/Intellisense/Insert Snippet menu
  • Shortcut – this is the text you want to type to execute the snippet. Be careful not to select something that might already be in use (like foreach)
  • Snippet – this is the text that will be inserted into the document. The Language attribute determines where the snippet appears in the Edit/Intellisense/Insert Snippet menu. The text you want to appear in the document should be inserted where the xxx is in the following sample – ![CDATA[xxx]]

Once you have updated the document, you have to save it to a particular location on your machine. That location is %UserProfile%\Documents\Visual Studio 2012\Code Snippets\Visual Web Developer\My HTML Snippets. This code will work for your machine if you are using VS 2012. NB: Replace the Visual Studio 2012 section of the text accordingly if you are using a different version of VS.

Once you have saved the file, you should be able to type the text that you entered in the Shortcut attribute of the XML file and your Snippet Code will be inserted.

Til next time…

Leave a Reply

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