Visual Studio 2010 code snippets

Snippet is a programming term for a small region of re-usable source code, machine code or text. Ordinarily, these are formally-defined operative units to incorporate into larger programming modules. Snippets are often used to clarify the meaning of an otherwise "cluttered" function, or to minimize the use of repeated code that is common to other functions.

 

Visual Studio 2010 code snippets

Loading the Snippet into Visual Studio:

There are two ways to insert the above snippet into Visual Studio.

The most straightforward way is to 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. For my example, the snippet goes under Visual C#. Once put here, VS 2010 automatically picks up the snippets without the need to restart.
 
The second option is to import the .snippet file into Visual Studio.
- Inside Visual studio, go to Tools->Code Snippets Manager (Ctrl+K,Ctrl+B). This brings up the Snippets Manager.
- Press Import button, and navigate to the location where the snippet was saved. Select the .snippet file.
- Press OK.

Using the Code Snippet:

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

Visual Studio 2010 code snippets

You can also press Ctrl+K and Ctrl+X which brings up the "Insert Snippet" menu as shown below:
Visual Studio 2010 code snippets
We can navigate to My Code Snippets, and select the TryCatchFinally that we’ve just added:
Visual Studio 2010 code snippets

The Snippet Designer

The Snippet Designer is an open source plugin which enhances the Visual Studio IDE to allow a richer and more productive code snippet experience.

The Snippet Designer supports both Visual Studio 2010 and Visual Studio 2008.  For the 2008 download please visit the Snippet Designer Codeplex  page.

For more information visit the Snippet Designer Codeplex page at http://snippetdesigner.codeplex.com

For information about new releases check Matthew Manela's blog

Features

A Snippet editor integreated inside of the IDE.

  • Access it by opening any .snippet file or going to File -> New -> File -> Code Snippet File
    It uses the native Visual Studio code editor so that you can write the snippets in the same
    environment you write your code.
  • It lets you easily mark replacements by a convenient right click menu.
  • It displays properties of the snippet inside the Visual Studio properties window.

 Snippet Editor

A Snippet Explorer tool window to search snippets on your computer

  • It is located under View -> Other Windows -> Snippet Explorer
  • This tool window contains a code preview window which lets to peek inside the snippet to see what it is without opening the file.
  • Maintains an index of snippets on your computer for quick searching.
  • Provides a quick way to find a code snippet to use, edit or delete

 Snippet Editor

 

A right Click "Export as Snippet" menu option added to C#, VB and XML code editor to send highlighted code directly to the Snippet Editor

 Snippet Editor

 

Shortcut Description Type Insertion Locations
#if #if/#endif directive E, S Anywhere
#region #region/#endregion directive E, S Anywhere
~ destructor E Inside a class
Attribute attribute (using recommended pattern) E Inside a namespace (including the global namespace), a class, or a struct
checked checked block E, S Inside a method, an indexer, a property accessor, or an event accessor
class class declaration E, S Inside a namespace (including the global namespace), a class, or a struct
ctor constructor E Inside a class
cw Console.WriteLine E Inside a method, an indexer, a property accessor, or an event accessor
do do...while loop E, S Inside a method, an indexer, a property accessor, or an event accessor
else else statement E, S Inside a method, an indexer, a property accessor, or an event accessor
enum enum declaration E, S Inside a namespace (including the global namespace), a class, or a struct
equals implementing Equals() according to guidelines E Inside a class or a struct
Exception exception E Inside a namespace (including the global namespace), a class, or a struct
for 'for' loop E, S Inside a method, an indexer, a property accessor, or an event accessor
foreach foreach statement E, S Inside a method, an indexer, a property accessor, or an event accessor
forr reverse 'for' loop E, S Inside a method, an indexer, a property accessor, or an event accessor
if if statement E, S Inside a method, an indexer, a property accessor, or an event accessor
indexer indexer declaration E Inside a class or a struct
interface interface declaration E, S Inside a namespace (including the global namespace), a class, or a struct
invoke safely invoking an event E Inside a method, an indexer, a property accessor, or an event accessor
iterator simple iterator E Inside a class or a struct
iterindex 'named' iterator/indexer pair using a nested class E Inside a class or a struct
lock lock block E, S Inside a method, an indexer, a property accessor, or an event accessor
mbox MessageBox.Show (requires reference to System.Windows.Forms) E Inside a method, an indexer, a property accessor, or an event accessor
namespace namespace declaration E, S Inside a namespace (including the global namespace)
prop automatically implemented property E, V3+ Inside a class or a struct
propfull property and backing field E Inside a class or a struct
propg autoproperty with a 'get' accessor and a private 'set' accessor E, V3+ Inside a class or a struct
sim 'static int Main()' method declaration E Inside a class or a struct
struct struct declaration E, S Inside a namespace (including the global namespace), a class, or a struct
svm 'void Main' method declaration E Inside a class or a struct
switch switch statement block E Inside a method, an indexer, a property accessor, or an event accessor
testc MSTest test class E  
testm MSTest test method E  
try try catch block E, S Inside a method, an indexer, a property accessor, or an event accessor
tryf try finally block E, S Inside a method, an indexer, a property accessor, or an event accessor
unchecked unchecked block E, S Inside a method, an indexer, a property accessor, or an event accessor
unsafe unsafe block E, S Inside a method, an indexer, a property accessor, or an event accessor
using using block E, S Inside a namespace (including the global namespace)
while while loop E, S Inside a method, an indexer, a property accessor, or an event accessor

E - Expansion, S - Surrounds With (Ctrl-K, Ctrl-S), V3+ - Requires C# 3.0 or higher

Create Your Own Code Snippets in Visual Studio 2010 for MVC 2

One of the great new features in Visual Studio 2010 is the ability to now use code snippets inside of ASP.NET, HTML, and JavaScript files. Snippets have long been a productivity boost for regular C# code but have been sorely missing for mark up. In fact, frameworks like MVC 2 actually ship with their own snippets.

 Visual Studio 2010 code snippets

There are only about 10-15 snippets that are currently shipping with MVC (and many of those are just duplicated because there are both VB and C# versions).  That doesn’t seem like very many.  But let’s have a look at one that would be pretty common – the HTML helper for a text box:

Visual Studio 2010 code snippets

That snippet produces the following code:

 1: <%= Html.TextBox("FirstName") %>

Hmmm. That code doesn’t seem very “MVC2ish”.  First off, it’s using the old school double-quoted string to specify the property rather than the new strongly-typed lambda-based HTML helper. Secondly, it’s using the TextBox() method rather than the EditorFor() method.  Third, it’s using the old <%= syntax which Microsoft is trying to get us to forget exists, rather than the new <%: HTML encoding syntax.

The best approach here is for us to create our own snippets customized to our heart’s content. But the snippet files are not the easiest things to work with so rather than starting from scratch, let’s just grab the MVC textbox snippet and modify it. The snippets can be found in the directory: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Visual Studio 2010\Snippets\HTML\1033\ASP.NET MVC 2. I’m going to grab the “textboxmvc.snippet” file from there, create a directory called “My MVC2 Snippets” and put it inside of the normal code snippets directory structure for Visual Studio. So the full path will be: <My Documents>\Visual Studio 2010\Code Snippets\Visual Web Developer\My MVC2 Snippets. Then I’ll rename “textboxmvc.snippet” to “editorfor.snippet”.

In order to get Visual Studio to recognize this location, I need to do Tools –> Code Snippet Manager and select the directory:

Visual Studio 2010 code snippets

Next I’ll open the editorfor.snippet file in any code editor and change a few key lines:

 1: <CodeSnippet Format="1.1.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
 2:  <Header>
 3:  <Title>editorfor</Title>
 4:  <Author>Steve Michelotti</Author>
 5:  <Shortcut>editorfor</Shortcut>
 6:  <Description>Markup snippet for an ASP.NET MVC EditorFor helper</Description>
 7:  <SnippetTypes>
 8:  <SnippetType>Expansion</SnippetType>
 9:  </SnippetTypes>
 10:  <ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325}</ProjectTypeGuids>
 11:  </Header>
 12:  <Snippet>
 13:  <Declarations>
 14:  <Literal>
 15:  <ID>property</ID>
 16:  <ToolTip>property</ToolTip>
 17:  <Default>property</Default>
 18:  </Literal>
 19:  </Declarations>
 20:  <Code Language="html" Key="*"><![CDATA[<%: Html.EditorFor(m => m$property$) %>$end$]]></Code>
 21:  </Snippet>
 22: </CodeSnippet>

Line 3, 4, 5, and 6 are simple and straight-forward replacements.  The primary line I need to change is line 20. I’m going to use the generic “m” (for “Model”) for my lambda identifier and then use a replacement variable called $property$ (which I also specify on lines 15-17). I intentionally left out the “.” because after the snippet expands, I want the next keystroke I press to be the “.” so that intellisense will naturally come up for me (this snippet can be expanded without the mouse by typing “<edi”):

 Visual Studio 2010 code snippets

Just hit <Enter> and you’re all done!

Reference

More .NET Cheat Sheets

.NET Format String Quick Reference

Visual Studio Built-in Code Snippets

ASP.NET 2.0 Page Life Cycle & Common Events


Other Cheat Sheet Links

Summary

Visual Studio 2010’s code snippets stay on the correct side of that line, being nothing more really than some macro expansions that could easily be defined in just about any text editor. If you have to copy-n-paste share, or find yourself writing code that is almost the same (and doesn’t lend itself to code generation) then snippets might be just your thing. They are especially nice if you want to share code/snips with your team.

Visual Studio 2010 code snippets

Comments (7) -

  • Sorry, I meant ReSharper.
  • Thank you very much, but I just wanted to know your opinion. Do you prefer VS 2010 snippets over ReSharper live ones? Do you use R# at all?
  • Yes, I like re-sharper and have 3 years experience on it. Currently Visual Studio 2010 support almost all snippets from this tool, version 5.1 is really comfortable for code re-factoring, but for writing code VS is forever.

Add comment

Loading