In the developing process of applications that are not as small as the typical "Hello, World!" examples, there are a variety of factors than can lead to important time savings.

There's a lot of documentation out there on how to design and specify application before the coding process starts, but there is a crucial factor on success that is not usually spoken of: the way you manage, create and edit your source files.

And of course there are some beautiful software pieces to help developers in that process. They're called IDEs (Integrated Development Environment).

The problem with most of those IDEs is that they offer so many options that you usually have to read a user's manual to really take the best from them. Ok, this is something normal, you might say. Maybe you're right, but be honest, how many software user guides have you read in your life? And I'm not talking about the usual RTFM for a linux man page which can be 4 pages long at most. I'm talking about a user's manual of 500 pages. I haven't.

And that's the reason today I'll be talking about a nice feature I found on one of the most powerful IDEs out there (regardless of being from Microsoft): Visual Studio 2005 Code Snippets.

Code Snippets are more than just snippets of code, to start with. It's not a simple code listing to quickly paste into your files, because Code Snippets are smart and adaptative, this is, they can be parametrized. Let's see this in a simple example.

Imagine you want to code a for loop. All those kind of code structures behave the same way: there's an initial condition, an ending condition, a condition modifier so you eventually leave the bucle, and of course the body, the code you want to be executed every time the bucle takes place. And it's not unusual to use an integer variable to manage the counter which controls how many times that piece of code will be executed, for example the index of an array and the size of that array. You would code something like this:

int length = someArray.size();

for (int i = 0; i < length; ++i)
{
    doSomething(array[i]);
}

Ok, this is a shot piece of code and it takes about 10 seconds to write it, but it would be better if some IDE feature could help us. This is where Code Snippets come into action. Let's do this exact thing using Code Snippiets.

  1. Go to the part of the code you want to place the bucle in and press the right mouse button to select the Insert Snippet option.
  2. Select the for on the list box.
  3. You'll see the basic structure of the code has already been typed for you.

Inserting a snippet Inserting a snippet (2) Inserting a snippet (3)

But this is not the end of the story!

With the tab key you can now navigate through the index variable and the ending condition of the bucle to type whatever you want there. Pressing enter will end the snippet wizard, and voilá, you have your for bucle coded, and only the body needs to be filled.

This example is kind of basic and you probably could code this far quicker by hand than by having to press mouse buttons and cursor arrows. You may be right, but as you may have already seen, there are plenty of snippets than can help you really improve your coding speed for all those "always the same" code structures. One good example of it is the property definitions on a C# class.

But code snippets not only can add code to a blank line, they can also sorround existing code to add features on it. Imagine you 've started coding a method and you realize later that there is some kind of exception you should be dealing with. You know what that means, going to the upper part of the code, typing the try {, going down, close the bracket, and probably indenting the bracketed code to have a pretty printed code. Not to mention you should probably have to add a catch or finally clause after, too. This is work that can be tedious and it is not done in 10 seconds as a for bucle. Code Snippets can help us here too.

  1. Select the code you want to sorround with a try/finally clause.
  2. Click the right mouse button and select Sorround With.
  3. Select the tryf snippet.

Sorrounding with snippets Sorrounding with snippets (2) Sorrounding with snippets (3)

One of the most interesting things about Code Snippets is that you can create your own for repetitive or tedious tasks you use to code. Let's see how to proceed to create a custom Code Snippet.

To begin with, a Code Snippet is an XML file. It's basic structure is the one following:

<codesnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <codesnippet format="1.0.0">
        <header>
           
        </header>
        <snippet>
            <code language="CSharp">
                <!--[CDATA[MessageBox.Show("Hello World");]]-->
            </code>
        </snippet>
    </codesnippet>
</codesnippets>

The element names are pretty self explanatory. You can customize the title of the snippet, and put the static code in a CDATA element, previously defining the language you'll be using.

You can add Literals and Objects to the snippet code too. Literals are pieces of the snippet the programmer will usually want to replace, such as variable names and similar items. Objects are elements that the snippet needs but they usually are objects previously defined in your code that you want the snippet to use, such as specific objects to work with. You'll understand this better with an example.

Let's suppose you want to create a code snippet that checks a specific web request variable to validate against a custom SQL Injection class you've programmed. For simplicity's sake we'll suppose the validation class is already programmed and has a method that does this security feature. In this case, the literal could be the variable name of the web request, and the object could be the SQL Validator class instance you've previously defined in your code.

Both literals and objects are defined inside the Declarations node in the snippet XML as follows:

<declarations>
    <literal>
        <id>requestName</id>
        <tooltip>Replace with the variable name of the HTTP Request</tooltip>
        <default>action</default>
    </literal>
    <object>
        <id>SqlValidator</id>
        <type>MyProject.Data.Validation.SQLValidator</type>
        <tooltip>Replace with a SQLValidator object in your application.</tooltip>
        <default>sqlValidator</default>
    </object>
</declarations>

As you can see, you can define an identifier, a tooltip and a default value, and in the Object element the class of the object.

Now the only thing you have to do is replace in your code snippet the pieces of code where you want those literals and objects to appear like this:

<code language="CSharp">
        <!--[CDATA[
            string variableRequested = Request["$requestName$"];
            if (!$SQLValidator$.Validate(variableRequested))
            //Insert error handling here
        -->
</code>

So, the final snippet would look like this:

<codesnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <codesnippet format="1.0.0">
        <header>
           
        </header>
        <snippet>
            <declarations>
                <literal>
                    <id>requestName</id>
                    <tooltip>Replace with the variable name of the HTTP Request</tooltip>
                    <default>action</default>
                </literal>
                <object>
                    <id>SqlValidator</id>
                    <type>MyProject.Data.Validation.SQLValidator</type>
                    <tooltip>Replace with a SQLValidator object in your application.</tooltip>
                    <default>sqlValidator</default>
                </object>
            </declarations>
            <code language="CSharp">
                <!--[CDATA[
                    string variableRequested = Request["$requestName$"];
                    if (!$SQLValidator$.Validate(variableRequested))
                    //Insert error handling here
                    -->
            </code>
        </snippet>
    </codesnippet>
</codesnippets>

Now you just have to copy this snippet in your custom snippet folder (usually in Visual Studio 2005 folder created on My Documents) and you'll be able to use it from the Visual Studio menu as any other one, or use the Code Snipper Manager on the Visual Studio Tools menu.

For more information about Code Snippets you can visit the MSDN page http://msdn2.microsoft.com/en-us/library/ms165393(VS.80).aspx.