Try our list of Frequently Asked Questions below to answer questions that you might have about code snippets.
Don't see the one you need? Then add a comment to this blog or post to the Visual Basic Forum. We'd love to hear from you!
1) What is an IntelliSense code snippet?
An IntelliSense code snippet is a fragment of code that can be inserted into the code editor to accomplish a particular task. Unlike samples, which help by demonstrating a concept in an example, code snippets help by actually accomplishing the task in the context of your own code. There are a few different types of code snippets:
Task-oriented code snippets help the user accomplish a particular code task. These code snippets include one or more lines of code that accomplish a specific task such as writing a message to the application event log, comparing two files or sending an email message.
Expansion code snippets reduce the number of keystrokes required to implement common programming constructs. These code snippets do not include any application specific code and contain the minimum code required by the construction. Examples of expansion code snippets include an If statement, For loop, Property declaration, Try…Catch block, etc.
Code snippets involve more interactive features than just a simple block of code. For example, inserting a code snippet into a source file automatically adds the associated references and imports statements. When the code snippet code gets inserted, various replacement fields appear highlighted. These fields are linked and contain tooltip instructions to allow for easy adaptation of the snippet code to the context of the snippet’s insertion. This functionality is all specified in the code snippet file itself.
2) Does VS have some pre-installed IntelliSense code snippets? Where can I find them?
Yes. Visual Studio 2005 comes with a large number of VB IntelliSense code snippets installed. The range is between 233 code snippets for Visual Basic Express Edition and Visual Web Developer Express Edition and 417 VB code snippets for Visual Studio Tools for Office.
The code snippets manager (found in the Tools menu) displays a list of these files for you, along with the directories in which they are located.
To find these files on disk, look at the location field that is listed in the code snippets manager for each file. For VB Express, files get installed by default to \Program Files\Microsoft Visual Studio 8\Common7\IDE\VBExpress\Snippets\1033\. The default location for higher Visual Studio 2005 products is \Program Files\Microsoft Visual Studio 8\VB\Snippets\1033\. However, we encourage that you place your own code snippets in your My Documents folder, rather than into Program Files. A code snippet directory already gets created there for you: My Documents\Visual Studio 2005\Code Snippets\Visual Basic\My Code Snippets.
You can also search through the set of pre-installed code snippets, when going to insert one in the editor. Either right-click and choose “Insert Snippet…” or type “?” followed by the Tab key in your text editor to invoke the code snippet inserter. A directory structure will appear inline with your code, which you can navigate and browse for snippets.
3) How do I use an IntelliSense code snippet?
To insert an IntelliSense code snippet into your code, either right-click and choose “Insert Snippet…” or type “?” followed by the Tab key to invoke the code snippet inserter. A directory structure will appear inline with your code, which you can navigate and browse for code snippets. Once you find the title of the code snippet you want to insert, either double-click or press Enter to insert it into your file.
If the code snippet has replacement fields, they will appear highlighted in green. Press Tab to navigate through the replacement fields, updating them as you go. If you already know what you want to replace the field with, you can just type over the selected text. Other occurrences of the replacement will update automatically. To view a list of potential replacement choices, type Ctrl+Space while the replacement field is selected and an IntelliSense completion list will arise. This list will provide you with names of other variables in your code that are of the correct type for this replacement. If appropriate, you will also have the option in this list to create a new variable of the required type.
4) How do I do a keyword expansion?
A keyword expansion is a quick way to enter an IntelliSense code snippet in your code. The code snippets pre-installed with VS each have a shortcut associated with them; you can see them in the code snippets manager.
To enter a code snippet in your code, simply type the shortcut (keyword) associated with it in the text editor and press the Tab key.
If you don’t remember exactly the shortcut for your code snippet, you can just enter a few letters in the code editor followed by ‘?’ and Tab, and VS will display an alphabetical list of shortcuts, with the one starting with the letters you entered selected.
You can scroll through this list and insert the code snippet corresponding to the shortcut you select.
5) Where else can I find IntelliSense code snippets?
IntelliSense Code snippets can also be found online. If you’re looking for a particular code snippet try to search the internet using some keywords describing the task you want the code snippet to accomplish.
Some Codezone partner sites also offer download pages with an option to filter their contents for ‘code snippets’ or just ‘snippets’.
Check out also the Microsoft Visual Basic Developer Center. Currently, the dev center page devoted to code snippets posts information about the feature, but in the future, it will also host snippets for download.
6) Where can I find more resources on IntelliSense code snippets?
Helpful code snippet resources include:
Introduction to IntelliSense Code Snippets: a help topic which describes the Code Snippets feature, and contains helpful links for using and creating Code Snippets.
Code Snippets Schema Reference: a help topic which lists and describes the XML schema elements for snippet files.
Microsoft Visual Basic Developer Center: a dev center page devoted to code snippets. Currently it posts information about the feature, but it will also host snippets for download in the future.
Visual Basic Forum: Read answers to questions that have been asked here about code snippets, or post your own!
This blog!: Check back here periodically for new tips and tricks about interacting with code snippets.
7) How can I write an IntelliSense code snippet? Where can I download the Snippet Editor from?
The easiest way to write your own IntelliSense code snippets is to use the Visual Basic Snippet Editor. It’s a free tool that lets you view, edit, create and save code snippets in a convenient way.
The download page also contains additional links and resources for the editor.
That said, code snippets are simply XML files, so if you’d rather follow a different approach you can also edit them with a generic editor. To learn more about the code snippet format check out the resources listed in the previous question.
8) What languages does the Snippet Editor support?
The snippet editor is mainly thought for Visual Basic IntelliSense code snippets, but it also has some C# support built in.
9) I’d like to make some changes to the Snippet Editor myself. Is there a way I can do that?
Yes. The Snippet Editor is a shared source project and was developed through the contributions of several people.
If you visit the Snippet Editor GotDotNet workspace you’ll find lots of useful resources. You can also download the latest Snippet Editor source code to work on your changes.
10) What are the most commonly used IntelliSense code snippets?
We don’t have official data about the most used code snippets, but here’s a list of the ones we think are the most useful and common between the ones installed with VS. They’re ordered by folders as they appear in the Code Snippets Manager. Each code snippet is followed by ‘;’ and its shortcut. To quickly insert the code snippet in your code, enter the shortcut in the code editor and press the Tab key:
Application - Compiling, Resources and Settings -> Load an Assembly at Run Time; appLoad
Application - Compiling, Resources and Settings -> Write to a Text File; appLog
Collections and Arrays -> Iterate through a collection; colIter
Collections and Arrays -> Locate an Element in an Array; arrLoc
Connectivity and Networking -> Create an E-Mail Message; conEmail
Data - Designer features and ADO.NET -> Create a Server based SQLConnection to SQL Server; adoCreateSqlConn
Data - Designer features and ADO.NET -> Create a Parameterized SELECT Command; adoSelectwParams
Data Types - defined by Visual Basic -> Convert an Array of Bytes into a String; typeByteStr
Data Types - defined by Visual Basic -> Parse an E-Mail Address; typeParseEmail
File System - Processing Drives, Folders and Files -> Copy a File; filCopyFile
File System - Processing Drives, Folders and Files -> Create a File; filCreateFile
File System - Processing Drives, Folders and Files -> Read Text from a File; filReadText
File System - Processing Drives, Folders and Files -> Write Text to a File; filWriteText
Math -> Get a Random Number using the Random Class; mathRand
Security -> Encrypt a String; secEncrypt
Security -> Find the Current User's Name; secUser
Windows Forms Applications -> Forms -> Determine which Control on a Windows Form is selected; formSelect
Windows Forms Applications -> Forms -> Display a Windows Form; formNew
Windows Forms Applications -> Controls and Components -> Add Menu Items to Windows Forms; menuAddItems
Windows Forms Applications -> Sound -> Play a Sound; sndPlay
Windows Operation System -> System Information -> Determine Desktop Display Resolution; sysRes
Windows Operation System -> System Information -> Determine the Windows System Directory; sysDir
XML -> Iterate named nodes in XML Document; xmlIter
XML -> Read XML from a File Using XmlTextReader; xmlReadTxt
11) What do the green highlighted areas mean?
The green highlighted areas denote replacement fields in the IntelliSense code snippet. These fields are formatted so that you can easily contextualize the code snippet to the task you are setting out to achieve in your own application. You can navigate between replacement fields by hitting Tab. You can also invoke an IntelliSense completion list to view potential replacements for the currently selected replacement by typing Ctrl+Space. Once the file is closed, the code is committed and the replacements disappear.
12) Are there different kinds of replacement fields?
There are two types of fields that can be turned into replacements: objects and literals. Object replacements are used for variable names when the variable declaration is expected to lie outside the IntelliSense code snippet. Thus, typing Ctrl+Space over these replacements will list names of other variables in your code that match the type of the current replacement. The completion list also contains an option to create a new object of the appropriate type, in case it does not yet exist in your code.
Literal replacements are used for values which do not have dependencies outside the code snippet. Common literal replacements include Strings, Numbers, and Enums. These values often need to be replaced in order to give the code snippet the desired behavior. Since literal replacements are used for values which do not have dependencies outside the code snippet, they do not include the same option in their intellisense list as for objects, to add a variable declaration outside the code snippet.
13) How long do the green highlighted areas (aka replacements) stick around? What makes them disappear?
Snippet replacements stay highlighted until you close the file. This allows you to use the replacement functionalities for the duration that you are working with the snippet.
Some of the replacement functionalities are:
- Linked replacements: renaming one replacement field will cause all other occurrences of the same replacement to update automatically.
- Intellisense completion lists: typing Ctrl+Space while a replacement is selected will invoke a completion list of potential options for the replacement.
14) How do I share IntelliSense code snippets?
IntelliSense code snippets are basically xml files with the .snippet extension in the file name. The code snippet file embeds some useful properties like Title, Author and Description. If these properties are set correctly, code snippet files should enclose all information necessary to describe them without any need for further documentation.
Code snippets can be e-mailed or uploaded to web sites.
To make life easier for users receiving your code snippets, our recommendation is to use the .vsi format. Vsi (Visual Studio Installer) packages allow users to just double-click on the file to start a wizard that will guide them through the installation process.
A .vsi package contains one or more code snippets and a .vscontent file, that describes the package and the code snippet files.
15) How do I create a .vsi package for IntelliSense code snippets?
The procedure to create a .vsi package is pretty simple:
- put all snippet files you want to include in your package in one directory
- download the Create_vscontent code snippet
- create a new VB Console Application in VS and insert the Create_vscontent code snippet into it
- make the 2 required replacements, build and run the console app. This will create the .vscontent file required for your .vsi package into the same folder where you have your code snippets
- in windows explorer go to the folder with the code snippets, select all of them together with the .vscontent file, right click and choose ‘send to’ -> ‘Compressed (zipped) folder’
- select the zipped folder that you just created and rename it to change its extension from .zip to .vsi
One note: the .vscontent file created with the code snippet you downloaded doesn’t allow you to customize the <DisplayName> field for each snippet, it just sets it to the snippet file name. If you want to provide a more descriptive value for this field, you can just open the .vscontent file in any editor and change the field before compressing the package.
16) How do I install a .vsi package containing IntelliSense code snippets on my machine?
To install a .vsi package just double click on it and a wizard will guide you through the installation procedure. On Beta2 drops, when the wizard starts, you may run into a known issue where the wizard throws an exception. To work around this problem open Visual Studio, open the Code Snippets Manager (Tools->Code Snippets Manager), then, keeping it open, double click on your .vsi package again to restart the wizard.
17) When do I use an IntelliSense code snippet vs. a component or API?
While a component API is normally used to accomplish one particular, highly specialized task and may consist of hundreds or thousands lines of code, code snippets have more of a ‘connect the dots’ characterization and should be used for simple tasks. You could use a code snippet to demonstrate how to use several apis in conjunction to accomplish a particular goal, e.g. reading the contents of a text file. Inserting a code snippet into code can have an educative purpose for the user, since she actually sees the code that implements a particular functionality. Code snippets also allow for a higher degree of customization because of the replacement fields.