Advanced Basics

IntelliSense Code Snippets

Lorenzo Minore

Code download available at:AdvancedBasics0604.exe(117 KB)

Contents

Inserting Code Snippets into Code
Code Snippet Customization
Managing Code Snippets
The Visual Basic Snippet Editor
Sharing Code Snippets
The Power of Snippets

IntelliSense code snippets are one of the coolest new features in Visual Studio® 2005. Code snippets are highly customizable code fragments intended to accomplish simple to intermediate tasks quickly; they can be inserted into your code with just a few keystrokes.

In this column I'll describe how to use the code snippets installed with Visual Studio 2005, how to edit the existing set or create your own, how to share your snippets with other users, and where to look for more samples.

Inserting Code Snippets into Code

Code snippets can be inserted in a variety of ways. If you're in the editor browsing for a code snippet, use the Code Snippet Inserter. You can invoke it by right-clicking in the editor and selecting the Insert Snippet... command from the context menu. In Visual Basic® you can also type "?", then hit the Tab key to obtain the same result. The Code Snippet Inserter has some features in common with the IntelliSense® UI; it lets you navigate the snippet directory structure to select the snippet you want to use (see Figure 1). Tooltips will appear beside the currently selected snippet to give you a description and the shortcut for it.

Figure 1 Code Snippet Inserter

Figure 1** Code Snippet Inserter **

For snippets that you use more frequently or for which you want quicker access, you can just type the shortcut in the editor, followed by the Tab key to insert them. To learn a snippet's shortcut, you can either select it in the Code Snippet Inserter and look at the tooltip, or view it in the Code Snippets Manager, which can be accessed via the Tools menu.

The shortcut+Tab insertion method also produces a neat effect for snippets that use keywords as their shortcuts. Type Select followed by Tab in your Visual Basic code and the Select-Case code snippet will be inserted (see Figure 2).

Figure 2 Select-Case Snippet

Figure 2** Select-Case Snippet **

If you only remember a part of the snippet's shortcut, in Visual Basic, you can type the beginning of the shortcut, type "?" followed by the Tab key, and a shortcut completion list will appear (see Figure 3). For example, to insert a Visual Basic snippet from the Application directory, you could type "app" (the shortcut prefix for that directory), or just "a" followed by "?", then hit the Tab key in order to invoke the list. When the shortcut list appears, the title of the snippet corresponding to the currently selected shortcut will be displayed in the tooltip. You can navigate the list, then double-click or press Enter to insert the selected snippet into your code.

Figure 3 Snippet Shortcut List

Figure 3** Snippet Shortcut List **

Visual Basic snippets can also be inserted in code through a simple drag and drop operation. If you know the location of a particular snippet file on disk, you can simply drag and drop it from Windows® Explorer directly into your Visual Basic code!

You can undo a snippet insertion; if you inserted the wrong snippet or invoked a shortcut by accident, just execute the undo command (Ctrl+Z) and your code will return to its previous state.

Code Snippet Customization

Code snippets are different from simple fragments that you can copy and paste into your editor.

When you insert a Visual Basic code snippet it will automatically add the referenced assemblies to the project and the required imports to the code file, so that your code will build properly (this feature, however, is not supported in C# code snippets).

What really makes code snippets so convenient to use is the replacement fields, green highlighted areas that identify the values you may commonly want to replace to fit the snippet to your specific task. You can use Tab and Shift+Tab to move back and forth through replacement fields. Each one has a tooltip associated with it that describes what it represents and how it should be replaced.

In Visual Basic, replacement fields also have IntelliSense support to help you make the right substitution; if you hit Ctrl+Space while in a replacement, a list of the local variables of the same type as the replacement will pop up, and you can pick one as your substitution. In C#, this key combination will bring up the same IntelliSense completion list you would see when typing ordinary code (see Figure 4).

Figure 4 Replacement Fields with IntelliSense

Figure 4** Replacement Fields with IntelliSense **

While you type in a replacement field, it will extend itself; if you want to keep typing without further extending that field, you can hit the Esc key, which lets you transition outside of the replacement.

Replacements can be linked; there may be multiple occurrences of the same one, and when you replace one, all the linked ones will be updated automatically as well.

In Visual Basic the replacement fields will stay highlighted as long as you don't close the code file and all associated files (that is, a Form's design view needs to be closed as well). In C#, once you press Enter, the replacement fields will be gone and your changes will be committed. Of course you can always make more changes later on; as the snippet becomes part of your code, though, you won't have the visual help of the highlighting or the other replacement field features.

Managing Code Snippets

Code snippets installed with Visual Studio are organized in a directory structure by the subject or task they accomplish. To see all directories and the snippets they contain, you can open the Code Snippets Manager. Simply select Tools | Code Snippets Manager (see Figure 5). This dialog lets you browse the snippet folders and displays useful information. When you select a snippet, you'll be able to see its physical location on disk, a short description of what it does, the shortcut, and the snippet author (which is Microsoft Corporation for all preinstalled snippets).

Figure 5 Code Snippets Manager

Figure 5** Code Snippets Manager **

The Add button in the Code Snippets Manager lets you add a whole folder to the root of the directory structure shown. This is a good way to add new snippets that you have stored in a directory on disk to your collection. The folder you're adding may contain some files that are not code snippets, but when you look at it in the snippet manager you'll see only subfolders and code snippets. Your current selection in the tree view doesn't affect where the new folder is added; it will always be a direct child of the snippet folders root.

The Import button lets you add one or more code snippets to the directory structure shown by the snippet manager. Once you select the snippets you want to import, you'll be able to choose the folders where you want to place these snippets.

The snippet directory structure contains a folder called My Code Snippets, where you should install your own snippets or the ones obtained from other users. If you want to make changes to some of the code snippets installed with Visual Studio 2005, it's a good practice to create a copy of the snippet in the My Code Snippets folder and modify it; otherwise it may be hard to revert.

To change the code snippets installed with Visual Studio without first copying them, you also need write privileges to the Program Files folder, which are normally granted only to administrators.

The Remove button will simply remove the currently selected folder from the directory structure shown by the Code Snippets Manager. The folder you remove won't be deleted from the file system, it will just be removed from the Snippets Manager's view. You can always use the Add command to get it back. The Snippets Manager view represents the snippets you'll be able to insert in your code editor through the snippet inserter or the other techniques described here, so if you remove a folder from this view, you won't have access to the snippets it contains in the IDE.

The Search Online command will bring you to the MSDN® search dialog, where you can enter keywords and search for code snippets. Unfortunately, this feature doesn't always work quite as expected, and you may end up with results matching your keywords but not related to code snippets. If you're searching online, I suggest using a search engine and entering your keywords together with "code snippet" or "IntelliSense Code Snippet" as this should give you a more fitting set of results.

The Visual Basic Snippet Editor

You're not limited to the code snippets that come with Visual Studio 2005; you can write your own or obtain them from other people.

Code snippets are actually XML files that follow a specific format. To see what they look like, open a code snippet in an XML editor. If you want, one way to edit code snippets is to work on the XML directly. If you want to learn more about the XML format of code snippets, take a look at the MSDN Code Snippet Schema Reference.

An easier way to write or modify code snippets is using the Visual Basic Code Snippet Editor tool.

The Visual Basic Snippet Editor is a shared source project developed by the Visual Basic user community in conjunction with the Visual Basic team. One of the Visual Basic MVPs, Bill McCarthy, did most of the development and bug fixing for the editor and gave it the slick look it has today (see Figure 6).

Figure 6 Snippet Editor

Figure 6** Snippet Editor **

When you open the editor, you'll see the left-hand pane containing a tree view similar to the one in the Code Snippets Manager. A textbox above it also lets you filter for particular keywords. When you select a node in the tree view and right-click on it, you'll be presented with a context menu and different options to manage your snippets and directories.

Both the Snippet Editor and the Code Snippets Manager share the same information regarding the code snippets folders, so if you make a change in one of the two tools, it will be reflected in the other one.

The Snippet Editor gives you the option to remove a single snippet when you select it in the left pane. In this case, the snippet will be deleted from the file system, so be very careful with this command. You can either add a new empty snippet to one of the folders or open an existing one.

If you plan to modify one of the snippets installed with Visual Studio, I suggest you create a copy in the My Code Snippets folder and work on that one. Depending on the version of the snippet editor you have, the My Code Snippets folder may not be displayed by default in the tree view, but you can easily add this directory yourself. The snippet code will be shown in the editor view, and there is also a preview pane that shows you how the snippet is going to look when you insert it in code.

Below the editor window there are five different panes that let you further customize your snippet. In the Properties pane you can modify the snippet's Title, Shortcut, Description, Author, Language, Scope, and Help URL. Most of these are self-explanatory. The Scope property refers to the code construct represented by the snippet—whether it's a class declaration, a member declaration, or part of a class member body. This can be a bit misleading because you may think that the scope is where the snippet lives instead of what the snippet represents. The Help Url property isn't enabled; it will be saved in the snippet file, but currently it won't be shown anywhere in the Visual Studio IDE. Other users will be able to see it if they open your snippet with the editor.

In the Replacements pane you can browse through replacement fields and modify their properties, or you can create new ones. Some replacement properties are not supported in all languages; the Function and Editable fields are supported in C#, but not in Visual Basic.

To create a new replacement, you can simply select the code in the editor and click on the + button in this pane. The Snippet Editor also allows you to create linked replacements; it will do so automatically if it finds expressions matching the one you selected in the snippet code. The Replacement Kind and Type properties are used in Visual Basic to provide IntelliSense for that field, so make sure to set them correctly if you want to enable this feature.

The References and Imports panes let you specify the referenced assemblies and Imports statements associated with the snippet you're authoring. These will be automatically added to your project and code file when you insert the snippet. This feature is currently supported only in Visual Basic. The Test pane lets you compile the code snippet inserted in the right scope and check for errors.

The Options dialog in the Snippet Editor can be used to customize the editor font and appearance and to select which languages you want to use. The language choice affects the snippets shown in the tree view and the keyword colorization in the code editor. Another interesting feature is the Save as .vsi command. This option lets you save a code snippet as a VSI (Visual Studio Installer) file. This is the recommended format for sharing community content, and makes installing new code snippets very easy.

For further information on how to use the editor, you can download the documentation from the Snippet Editor workspace. Here you can also file bugs or request new features for the editor and download the source code. You should also check out Snippy, another tool for creating code snippets, created by Gus Perez.

Sharing Code Snippets

Two Web sites that host code snippets are DotNetJunkies and GotCodeSnippets. Both sites currently have a limited number of code snippets available, but I expect these to increase significantly over the next few months.

The code snippets you download from there are in .vsi format. Once you have downloaded the .vsi package, double-click it and a wizard will guide you through the installation process, asking you, among other things, in which folder you want to place the snippets (see Figure 7). Again, I suggest separating snippets you download from the Web or obtain from other developers from the ones created by Microsoft; you can do so by placing them in the My Code Snippets folder.

Figure 7 Screen from the Visual Studio Content Installer

Figure 7** Screen from the Visual Studio Content Installer **

If you're planning to publish or share your own code snippets, I'd recommend using the .vsi format as well; this will make installation for your target audience easiest. To create a VSI with multiple snippets, the easiest way is probably to use Craig Skibo's Content Installer Powertoys, available on GotDotNet. The Content Installer Tool will walk you through the process of creating a Visual Studio Installer Package with multiple code snippets. This tool actually supports creating packages for other content types as well.

The Power of Snippets

Give code snippets a try. The ones included in Visual Studio provide a wide variety of productivity-enhancing solutions. However, the real power of this feature is its extensibility. The snippet editor, the code snippet hosting sites, and the VSI format and tools provide a framework for the user community to create a diversified code snippet library accessible to everyone.

Send your questions and comments to  basics@microsoft.com.

Lorenzo Minore is a Software Design Engineer for Microsoft on the Visual Basic team, working on the data design time experience in Visual Studio. He also coordinates a team to promote IntelliSense code snippets in the Visual Basic user community. Reach Lorenzo at lorenzom@microsoft.com.