How to Use Code Snippets in Visual Studio 2010

VS 2010 improves the snippet functionality, and makes it easier to create code snippets. There’s two types of snippets:

– Expansion snippets are inserted at the cursor
– SurroundsWith snippets wraps around selected code

 

Insert a new XML file to the project and make sure the file name ends with .snippet.

Right-click on the editor window and select Insert Snippet->Snippet, this inserts a template. By default the template contains both snippet types. We usually create an Expansion snippet so get rid of the <SnippetType>SurroundsWith</SnippetType> tag

Update the Title, Shortcut and Description.

Literal tag enables us to define editable values that are inserted into the snippet.

The code section contains what will be added when the snippet is inserted. Change the language to "CSharp", and enter your code snippet after <![CDATA[    and before  ]]>

Loading the Snippet into Visual Studio

You can put the .snippet files in VS 2010′s code snippets directory. The default location for it is C:\Users\<UserName>\Documents\Visual Studio 2010\Code Snippets\. This folder contains sub-directories based on the language of the snippet.  VS 2010 automatically picks up the snippets without the need to restart.

Or

Import the .snippet file into Visual Studio. Ctrl+K,Ctrl+B brings up the Snippets Manager. Press Import button, and navigate to the location where the snippet was saved.

Using the Code Snippet:

Type the name of the snippet (the shortcut), and pressing tab expands it.

Or

You can also press Ctrl+K , Ctrl+X which brings up the "Insert Snippet" menu.

Advertisements