Creating and using code snippets

I really like working in Visual Studio, and love the new features and user friendly tips and tricks to make my work more easy, today i would share one of the features that I really appreciate in Visual Studio is “code snippets”. Code snippets help you to speed up the development by giving you shortcuts to frequently used code.

For example if you want to create a for loop, you simply type for and press the “TAB” button twice.

Visual Studio will then automatically generate the code for you as you can see below.

By using the tab key, you can navigate to the marked words which enables to specify your own names.
That’s not all. The nicest thing about code snippets is that you can create your own code snippets.
In the following example, I’ll show you how.
Create a new file cend.snippet within Visual Studio 2005 and save it under the …\My Documents\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets folder.

Copy the following code in the file, I’ll explain the code in a minute:

<!–?xml version=”1.0″ encoding=”utf-8″ ?>
<CodeSnippets xmlns=””&gt;
<CodeSnippet Format=”1.0″>
<Title>End console</Title>
<Description>Code snippet for ending a console application</Description>
<Default>Press any key to continue … </Default>
<Code Language=”CSharp”>

Save the file and open a C# application. In one of the .cs files, type cend which will popup the intellisense menu.

When you press the “TAB” key twice, the following code will be generated:

How does it work:
The second line in the snippet file informs Visual Studio to use an xsd to help you by providing intellisense (the xsd is located in C:\Program Files\Microsoft Visual Studio 8\Xml\Schemas\1033\snippetformat.xsd depending on where you installed VS):


The shortcut contains the shortcut that you can use to reference to your code snippet. You can also reference the code snippets via the menu or via the Ctrl+K, Ctrl+X combination.

A literal is a variable that can be used within your code snippet. When using the code snippet, each literal is a placeholder for user input. You can add a default value as done in the sample.

Within the code element, comes the real code snippet. It is embedded in a CDATA element to be able to include special elements in the xml document.

It is also possible to create multiple snippets (1 snippet per file) 🙂

Reference : Geert Verhoeven Blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s