Creating and Using Code Snippets in Visual Studio 2005
By Scott Mitchell
Introduction
If you create your web applications using Visual Basic, you're likely aware that Visual Studio .NET 2002/2003 provides some
nice auto-complete features that were sorely missing from the C# side. For example, when creating a class in Visual Studio .NET 2002/2003
using Visual Basic, by merely typing in Public Property propertyName As Type and hitting Enter,
Visual Studio automatically expands the code to include both the Get and Set accessors:
Public Property propertyName As Type
Get
End Get
Set (ByVal Value As Type)
End Set
End Property
Visual Basic's auto-complete also was present in writing loop constructs, conditionals, methods, classes, enumerations, and
so on. While not as profound a time-saver as IntelliSense, Visual Basic's auto-complete support definitely speeds things up.
When moving from a Visual Basic project to a C# project in .NET 1.x, it always feels like I'm walking through mud, having to
enter the full syntax for properties and control-flow constructs. (You can circumvent C#'s lack of auto-complete, as well
as enhance Visual Basic's, through the use of macros. For more information on macros in Visual Studio .NET 2002/2003,
check out Improving Developer Productivity with Visual Studio
.NET Macros.)
The good news is that Visual Studio 2005 provides a remedy for its predecessors' lack of C# auto-complete support.
In VS 2005, not only can you utilize auto-complete in C#, you can also customize the auto-complete logic, building your
own auto-completion shortcuts. These shortcuts are called code snippets, and are defined via XML files that you can
create on your own, share with your colleagues, and import others' snippets from the web. On top of that, Visual Studio 2005's
code snippets can include portions whose values depend on the context with which the snippet is entered, or be marked as
to be completed by the developer using the code snippet.
In this article we will look at the code snippet feature in Visual Studio 2005. By the end of this article we'll see how
to use code snippets, how to import others' snippets, and how to create our own. Read on to learn more!
(For more information on Visual Studio 2005, check out the Using
Visual Studio section of the Recommended ASP.NET 2.0 Articles page!)
Using Code Snippets
Using code snippets in Visual Studio 2005 can be done in one of two ways:
By right-clicking and selecting Insert Snippet or
Surround With from the context menu (note: Surround With does not appear in the context menu for Visual Basic files), or
By typing in the code snippet's shortcut and hitting Tab.
Each code snippet can have a shortcut associated with it that, when typed in, automatically injects the snippet's code.
The latter approach is often quicker than the former, which requires using the mouse and drilling through a series of code
snippets in a listbox interface, but in order to use the shortcut approach you must, obviously, know the shortcut. So when
first familiarizing yourself with code snippets, it's usually helpful to use the context menu. (For more information on
injecting code snippets into your code, check out How to:
Insert Snippets Into Your Code (Visual Basic).)
For example, imagine that you creating a C# class to model the business objects in your web application, and need to define
a number of properties. Again, in Visual Basic, the auto-complete feature allows you just to enter Public Property propertyName As Type.
With C#, you must use a code snippet. In the class, right-click and choose Insert Snippet. This will display a drop-down list
of all of the registered code snippets. To add a property, choose the prop code snippet as shown below.
Upon selecting this code snippet from the drop-down list, the following text will be automatically injected into the class
where the cursor was positioned:
private intmyVar;
public intMyProperty
{
get { return myVar; }
set { myVar = value; }
}
Hitting the tab key you can move between the green sections, customizing the
code snippet. Updating the type in the private member variable, for example, automatically updates it in the
property statement; ditto for the member variable name.
The shortcut for this code snippet is prop. Therefore, you can also inject this code snippet by manually typing
in the word prop and hitting the Tab key. (C# includes the code snippets in the standard IntelliSense
drop-down list; with Visual Basic, you can hit the ? key after typing in the first few letters to see a list
of matching code snippets.)
Snippets are not just reserved for property accessors. As we will shortly see, Visual Basic offers a number of code snippets
that contain a few lines of code for accomplishing common tasks, such as reading Microsoft Access data into a DataSet,
or reading the text from a file. And since you can create and share your own code snippets, there's no reason why you can't
build snippets for those common chunks of code that are unique to your company's application or development practices.
The Built-In Code Snippets
Visual Studio 2005 ships with a number of language-specific code snippets. To explore the available code snippets, go to the
Tools menu and choose Code Snippet Manager (see the screenshot below). From here you can select which language you are interested in - Visual Basic,
Visual C#, Visual J#, or XML - and then drill into the available code snippets. Visual C# contains just a handful of code snippets -
a set of Refactoring snippets along with some fairly basic control-flow snippets and common patterns. Visual Basic boasts a
richer library of code snippets, with code snippets for generating random numbers, working with the file system, performing
common mathematical computations, encrypting and decrypting strings, convertions between data types, and so on.
For each code snippet, the Code Snippet manager shows the snippet's description, shortcut, and author. Additionally, the location
of the snippets are revealed in the Location textbox. As we will see later on in this article, each snippet is actually an
XML-based file with the .snippet extension. Since each snippet is an individual text file, you can easily modify
existing snippets, add your own new ones, or import other's snippets. But I'm getting ahead of myself here... before we dive into
creating and sharing code snippets, let's first look at how snippets are stored on the file system as well as the markup
used to express the code snippet itself.
The Inner Workings of a Code Snippet
A code snippet is simple an XML-formatted file on the computer's file system that contains a .snippet extension
and has been registered through the Code Snippet Manager.
The markup in the .snippet file provides the meta-data about the snippet - its description, shortcut, title,
what imports or references are needed (only supported in Visual Basic code snippets, unfortunately), and
so on - along with the actual meat of the snippet, which is the code that is injected when the snippet is applied. You can
examine the code snippets that ship with Visual Studio 2005 by navigating to the folder specified in the Location textbox
of the Code Snippet Manager (the snippets are stored at
C:\Program Files\Microsoft Visual Studio 8\LANGUAGE\Snippets\1033\ by default).
For example, the C# prop code snippet we looked at earlier in this article has the following markup (some
content has been clipped for brevity):
The code snippet contains two main portions: the <Header> and the <Snippet>.
In the <Header> you'll find the snippet's meta-data, the title, shortcut, type, description, and so on.
In the <Snippet> there required section is the <Code> section, which contains the
text injected by the snippet. The optional <Declarations> section is used to define replacable sections
in the snippet. Replacable sections are denoted with $name in the <Code> section and
are the sections displayed green and configurable by the developer using the snippet.
Importing Others' Code Snippets
Since snippets are just XML files, you can easily import others' code snippets. There are two ways to accomplish this:
If you have the .snippet file to import, simply go to the Code Snippet Manager and click the Import
button. This will bring up a dialog box, allowing you to navigate to the .snippet file on your hard drive.
Alternatively, you can install snippets by directly downloading a Visual Studio Community Content Installer file (.vsi).
VSI files are simply renamed ZIP files that Visual Studio 2005 can open and automatically install. There's a more
thorough discussion of VSI files, their format, and their use at Marie Hagman's blog entry
Community Integration in Whidbey Beta 2.
From the Code Snippet Manager you can click the Search Online button to look for code snippets available over the Internet.
This process is discussed in greater detail at How to: Search for Code Snippets Online.
Unfortunately, I've personally not been able to successfully find code snippets following these instructions. Has anyone else?
If so, let me know!
I have, however, been able to get code snippets from GotCodeSnippets.com,
a simple website that lists and allows visitors to search a publicly avaiable database of developer-provided code snippets.
These code snippets can be downloaded using the VSI format and therefore can be directly installed into Visual Studio 2005.
Creating And Adding Custom Code Snippets
While many common snippets can be found online at sites like GotCodeSnippets.com, there may be circumstances where you need
to create your own code snippets. As we've discussed, this involves creating a properly-formatted XML file with the .snippet
extension, and then Importing the snippet into Visual Studio. This process is discussed in detail in the
Creating Code Snippets section on MSDN. I don't intend
to have this article be an extensive examination of the code snippet syntax. The structure of code snippet files can be found
by exploring the existing code snippets, referring to the
MSDN documentation, or through the IntelliSense
Code Snippets FAQ.
In a previous article of mine, Improving Developer Productivity with Visual Studio
.NET Macros, I showed how to use a macro in Visual Studio .NET 2002/2003 to create an auto-complete statement for C#
for a property that used ViewState as a backing store. When developing custom ASP.NET server controls, developers typically need
to manually record all simply property values to ViewState using the following pattern:
public Type PropertyName
{
get
{
object o = ViewState["PropertyName"];
if (o == null)
return Default_Value;
else
return (Type) o;
}
set
{
ViewState["PropertyName"] = value;
}
}
With Visual Studio 2005, we can accomplish this with a code snippet. The following C# code snippet contains the complete markup.
To import this into your Visual Studio environment, simply download the .snippet file at the end of this article
and then, from the Code Snippet Manager, click Import and then browse to the snippet file. It's that simple! You can then
use the snippet in your custom server controls by simply typing in the shortcut (propvs) and hitting Tab.
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Property with ViewState Backing Store</Title>
<Shortcut>propvs</Shortcut>
<Description>Code snippet for property using ViewState as
its backing store.</Description>
<Author>Scott Mitchell</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>int</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>MyProperty</Default>
</Literal>
<Literal>
<ID>field</ID>
<ToolTip>The variable backing this property</ToolTip>
<Default>myVar</Default>
</Literal>
<Literal>
<ID>defaultValue</ID>
<ToolTip>The default value for this property.</ToolTip>
<Default>0</Default>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[
public $type$ $property$
{
get
{
object o = ViewState("$property$");
if (o == null)
return $defaultValue$;
else
return ($type$) o;
}
set
{
ViewState("$property$") = value;
}
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Create Snippets the Easy Way!
If you are creating Visual Basic code snippets and would prefer using a less angle-bracket approach, you can always try the free
Code Snippet Editor for Visual Basic 2005.
This WinForms application provides an interface for managing and adding code snippets without having to write a lick of
XML syntax.
Conclusion
In this article we saw how to use, manage, import, and create code snippets. Code snippets are a neat new feature in Visual Studio
2005 that marries the productivity-boosters of IntelliSense and auto-complete into a single paradigm. With code snippets you're
just a few short key strokes or mouse clicks away from that commonly-used block of code! You likely find IntelliSense an
indispensable feature of Visual Studio; I'm confident that you'll quickly find code snippets fall into this 'must-have'
category as well!