RSS Feed

Accelerate Your Coding with Code Snippets

Posted on Friday, January 16, 2009 in MAXoutput

by Brian Noyes

Brian_Noyes One of the most underutilized productivity features in Visual Studio 2005 and Visual Studio 2008 is Code Snippets. Even though most developers have heard about them, I find when working with consulting customers that there are few developers who use them on a regular basis. Even if they do use them, they vastly underutilize them by only using a couple of them and never create their own. In this article, I give you a quick intro into what code snippets are, how they work, what is available out of the box, and how to go beyond that by quickly creating your own code snippets.

Code Snippets Overview

Code snippets were introduced in Visual Studio 2005 and allow you to emit a chunk of code into your editor by typing a few keystrokes (a shortcut mnemonic). I’m going to use C# for the examples in this article, but just realize that code snippets work in Visual Basic and other .NET languages as well. That chunk of code can just be a static chunk of code, but what really makes code snippets powerful is that they can have placeholders that you can quickly overtype when you invoke the code snippet.

To try them out, the best one to start with is one you can probably use the most often: the prop snippet. Code snippets have both a title and a shortcut, although these will often both just be set to the shortcut value. The prop snippet emits a property with a backing member variable in Visual Studio 2005, or an auto-implemented property in Visual Studio 2008. Code snippets show up in the IntelliSense list as well, so if a snippet has a longer shortcut than a few letters, often you can just invoke it by typing a few of the letters and select it out of IntelliSense.

For example, if I go inside a class declaration and type prop and hit Tab twice (once to dismiss the IntelliSense list, the second time to invoke the code snippet), I get the following in the editor:

public int MyProperty { get; set; }

The type and property name will be highlighted in green, indicating that they are the placeholders defined in the snippet. For this snippet, the type is the first placeholder and will be selected so that if you start typing, you will overtype what is there. So for example, say I want a string property. I type string and hit Tab. Tab moves between the placeholders, and when the focus is placed on the next placeholder, it selects it as well so you can overtype with the value you want. So if I type Name and hit Enter, I leave the placeholder mode and my changes are accepted. If I keep hitting Tab, it revisits the placeholders in order in case you accidently tabbed past one or changed your mind as you were filling things in.

This one may not be stunning in its time savings, but when you add up the keystrokes (4 + 1 + 6 + 1 + 4 + 1) you have 17 versus the 30 for typing out the whole property yourself. Wham! You just became almost twice as fast at writing code! OK, don’t tell your manager just yet, you need to actually get used to doing this all the time first…

Now consider setting a switch case statement for an enumeration with a number of values. For example, say you needed to set up a switch/case on the states for System.Windows.Input.MouseAction. If you had a local variable of that type with something like the following method:

public void HandleMouseInput(MouseAction action)
{

}

If I go inside that method and type switch Tab Tab, I get the following snippet with a placeholder on the variable switch_on.

public void HandleMouseInput(MouseAction action)
{
  switch (switch_on)
  {
    default:
  }
}

If I type in action for the placeholder (the local variable of enum type MouseAction) and hit Enter, the snippet fills in all the enum values as case statements:

public void HandleMouseInput(MouseAction action)
{
    switch (action)
    {
        case MouseAction.LeftClick:
            break;
        case MouseAction.LeftDoubleClick:
            break;
        case MouseAction.MiddleClick:
            break;
        case MouseAction.MiddleDoubleClick:
            break;
        case MouseAction.None:
            break;
        case MouseAction.RightClick:
            break;
        case MouseAction.RightDoubleClick:
            break;
        case MouseAction.WheelClick:
            break;
        default:
            break;
    }
}

That is a huge keystroke savings filling all the tedious structure code! You just need to fill in what to do for each case.

Built-in Code Snippets

The list of built-in code snippets for C# is actually fairly short. There is really only a small number included out of the box. You can find the full list here with a short description of each for the core C# language snippets: (. There are some additional ones in other categories that ship with Visual Studio 2008, but the list is still fairly short for C#.  Visual Basic actually ships with hundreds. But this shouldn’t make you feel shorted as a C# developer. You can actually find a greatly expanded library of C# code snippets that shipped after VS 2005 here: . You can also find libraries of other code snippets out on CodePlex and other places on the net.  do, while, for, foreach, and a number of other common control structures are all in the basic set, along with everything from data access patterns to file IO patterns in the expanded sets. ctor is another one that is handy for declaring a default constructor for a class.

There is a Code Snippet Manager in the Tools menu of Visual Studio that will let you browse all the built in snippets, import new ones, and search online. However, if you understand what is going on under the covers, it is actually easier to just manipulate them as files.

Inside Code Snippets

Code snippets themselves are nothing more than XML files with a particular schema that reside in some directories that Visual Studio is aware of. Specifically, snippet files end with a (not surprising) extension of .snippet. The built-in code snippets that ship with Visual Studio reside under the folder C:\Program Files\Microsoft Visual Studio 9.0 under VC# or VB respectively. Visual Studio is the default editor for that file type, so you can just browse to those folders and double click on the .snippet files and edit the XML in Visual Studio. If you want to create your own snippets, put them in your Documents folder under Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets (or similar path for VB or 2005). Visual Studio watches this file all the time, so changes or additions to snippets take effect immediately without needing to restart Visual Studio.

There are a lot of elements supported in the schema but the key ones to focus on are Shortcut in the Header element, and the Declarations and Code elements under the Snippet element. Say I wanted to emit a code snippet like the following with a placeholder over the Boo! string so I could overwrite it:

System.Console.WriteLine("Boo!");

To do so, I would have a code snippet that looks like this inside:

xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Shortcut>cwbooShortcut>
    Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>outputID>
          <Default>Boo!Default>
        Literal>
      Declarations>
      <Code Language="csharp">
        System.Console.WriteLine("$output$"$end$);]]>
      Code>
    Snippet>
  CodeSnippet>
CodeSnippets>

In this case, the IntelliSense shortcut to invoke it is cwboo. The code snippet declares one literal variable named output with a default value of Boo!. The actual code of the snippet has to be declared inside an XML CDATA section because some legal characters in C #and other languages could cause XML parsing errors. The output literal is a named placeholder in the emitted code which will be replaced with the default value and highlighted for overtyping as discussed earlier. You can see that when you use a literal in the snippet, you enclose it within leading and trailing $ delimiters. Everything else in the snippet (except other variables) is emitted as plain text in the editor when the snippet is invoked. You can see I am also using a built-in literal $end$, which specifies where the input cursor is placed when you hit Enter to leave the placeholder mode of snippets.

Creating Your Own Snippets

By now you are probably emitting some form of "Eeewwww!!!" sound at the thought of editing the XML whenever you want to create your own snippets. The good news is that you don’t have to. There are a couple of free tools out there to help you create and edit snippets without ever needing to touch the XML directly. One I have been using for years as a C# guy is Snippy (http://www.codeplex.com/snippy). It puts a very simple dialog interface on top of the XML schema for you to create your snippets (see Figure 1).

snippy

Figure 1: Snippy

A great way to start many custom snippets is to start with an existing one and just edit it. Just remember to do a "Save As…" and save it to your Documents code snippets folder mentioned earlier so you don’t overwrite the built-in ones.

Another choice is the Code Snippet Editor for Visual Basic 2008 (). For those language bigots, you will have to get over the title: it actually supports multiple languages (see Figure 2).

CSEVB

Figure 2: Code Snippet Editor for Visual Basic 2008

Either one of these will allow you to quickly create your own snippets and stop typing the same code over and over again.

Code Snippet Functions

I showed you the switch snippet earlier in the article, and that may lead you down the path of thinking you can pull off anything with a snippet. Unfortunately that is one of the most powerful ones you will find. There is a whopping three functions in the C# library for expanded capabilities in your snippets (). The GenerateSwitchCases function is the one that did the magic for the switch code snippet. The ClassName function will emit the class name of the class in which the snippet is invoked. This is used by the ctor snippet I mentioned earlier to declare a default constructor. And lastly there is the SimpleTypeName function, which will take a fully qualified type name, and will emit both a using statement in C# (Imports in VB) and the root class name so that you don’t have fully qualified types in the emitted code. This is used by the built-in snippet cw, which emits a Console.WriteLine statement. Take a look at that built-in snippet if you want to see the way it is used. Unfortunately there is no way to add your own custom functions. If you want more power to do more custom things in your snippets, you might want to take a look at third party tools such as Developer Express CodeRush (http://www.devexpress.com/CodeRush) or JetBrains ReSharper (http://www.jetbrains.com/resharper/). They have things called templates that are like code snippets on steroids and are also extensible.

Wrap Up

Now you should have a good idea what code snippets are, how they work, and how to go beyond what you get out of the box. Let me share with you my approach to code snippets: If I find myself typing some code and I get that "déjà vu" feeling of "I know I’ve written this little chunk of code before", I stop myself, write it as a code snippet, and then I won’t ever have to write it again. Too often developers take the longer path because they think they will be "wasting time" by going and doing something like authoring a code snippet for the code they are writing. Many times, it is not authoring the code snippet that is the real waste of time.

—-

Brian Noyes is chief architect of IDesign (www.idesign.net), a Microsoft Regional Director and MVP, writer and speaker. He is the author of Developing Applications with Windows Workflow Foundation, Smart Client Deployment with ClickOnce, and Data Binding with Windows Forms 2.0. He is also a frequent speaker at conferences worldwide including Microsoft TechEd, DevConnections, VSLive!, DevTeach and others. You can contact him through his blog at .

Bring on the comments

  1. Johnny Programmer says:

    Your first sentence says it all … “One of the most underutilized productivity features”

    NO doubt one HUGE reason for this is the Microsuck morons put this p.o.s. out there and never made a decent editor for it.

    I have to count this as one of Microsucks 10 biggest failures. This is a half-implemented piece of crap in VS 2005, with NO IMPROVEMENTS in VS 2008, and probably won’t be any in VS 2010.

`

Bad Behavior has blocked 230 access attempts in the last 7 days.