here are some pieces of code that you write over and over again. Some of these pieces make sense as standard components or standard methods, such as logging or validation. Other pieces are more unique and cannot easily be made into standard methods, like Property procedures, For loops, or file input/output. For these bits of code, snippets are a perfect answer.
This article demonstrates how you can insert existing code snippets into your application, how to build your own snippets, and how to use the open-source Snippet Editor.
Inserting Code Snippets
A code snippet is a pre-built commonly used intelligent piece of code, sometimes referred to as an expansion template, which you can easily insert into a code window within the Visual Studio Integrated Development Environment (IDE).
Most code snippets are either common programming constructs, such as For loops, or common programming tasks, such as calling the ExecuteReader method of a SQLCommand object.
To insert a snippet into a code window, place the cursor where the snippet is to be inserted, right-click to display the context menu, and select Insert Snippet or type CTRL + K, then X. The Code Snippet Picker is then displayed for you to pick the desired snippet. To cancel the Code Snippet Picker, press the Esc key.
Snippets also have shortcuts to minimize the steps required to access a snippet. To insert a snippet using the shortcut, type in the shortcut and press the Tab key. The shortcut associated with a snippet is displayed in the tool tip of the Code Snippet Picker entry.
The snippets you have available depend on the language associated with the code window that has focus. If you are using Visual Basic, the Code Snippet Picker will appear as shown in Figure 1. Figure 2 shows the C# Code Snippet Picker. If you are in an XML code window, the Code Snippet Picker is as shown in Figure 3.
|
|
|
Let’s look at some specific examples. Say you want to add a property to a class. You could type all of the code to create your private member variable (or backing variable) and then your property getter and setter. But a more efficient way would be to use the property code snippet.
To accomplish this task in C#, display the Code Snippet Picker and then select the Visual C# > prop context menu item. Or, instead of using the Code Snippet Picker, use the shortcut by typing “prop” in the code window and then press the Tab key. (You may need to press the Tab key twice if the auto list members drop down is open.) The following code is automatically inserted into the code window.
private int myVar; public int MyProperty { get { return myVar; } set { myVar = value; } }
The highlighted portions of the snippet are called replacements. Focus is moved to the first highlighted replacement, shown in a highlighted rectangle. All like-named replacements are shown with a dotted rectangle. Edits cascade through the expansion, so when you change the replacement, all like-named replacements are changed to match. Tab between the replacements to change each one as needed.
In this example, the focus is initially moved to the data type of the private member. If you change the int to string, the data type of the property is also changed to string.
Press the Tab key to move to the private member variable name replacement and change it. The other references to that replacement within the snippet are then changed. Press Tab again to move to the property name replacement and change it as well.
When you have finished, the code appears like this.
private string _LastName; public string LastName { get { return _LastName; } set { _LastName = value; } }
Notice that the replacements remain highlighted, allowing you to tab through again and make further changes; however, as soon as you change anything else in the code window, the replacement highlights are removed and the code must be edited the old fashioned way.
To accomplish the same task in Visual Basic, display the Code Snippet Picker and then select Common Code Patterns, choose Properties and Procedures and then choose the Define a Property context menu item. Or, instead of using the Code Snippet Picker, access the shortcut by typing “property” in the code window and then the pressing the Tab key.
The question mark (?) character is also available in Visual Basic to assist with inserting snippets. Type ? and press the Tab key to display the Code Snippet Picker. Or, type the first letter(s) of the snippet shortcut, ? and then press the Tab key to display the list of shortcuts. The tool tip for each shortcut displays the name of the snippet.
When the property snippet is inserted into the code window, the following code is generated.
Private newPropertyValue As Integer Public Property NewProperty() As Integer Get Return newPropertyValue End Get Set(ByVal value As Integer) newPropertyValue = value End Set End Property
In the Visual Basic case, all occurrences of the replacements are highlighted and the one with focus is shown with a rectangle. Press the Tab key to move between the replacements. As in the C# case, edits cascade through the expansion. So if you change the data type replacement for the private member variable to a string, the property data types will automatically be changed to a string as well.
Unlike C#, all occurrences of the replacement are highlighted in Visual Basic, not just the first one. And the replacement highlights will remain on for further editing until the code window is closed.
C# and XML snippets have one additional feature called “Surround With” snippets. These snippets allow you to surround existing code with a snippet.
For example, say that you write the following code:
// Build the array string[] arr = new string[4] {"This","is", "a","test"}; string DisplayString=string.Empty; DisplayString += arr[0]; MessageBox.Show(DisplayString);
|
But you really want a loop around the code that builds the display string. To insert the loop using a snippet, select the code that is to be within the loop, select “Insert Snippet” from the context menu and then select “Visual C# for” from the Code Snippet Picker. Alternatively, you can select “Surround With” from the code window context menu and then select for from the list.
The resulting code is as follows:
for (int i = 0; i < length; i++) { DisplayString += arr[0]; }
Tab through the replacements to update them as needed and replace the arr[0] with arr[i] to complete the code.
If the snippet you insert requires a reference or import that you don't currently have set, the snippet will automatically add the reference and import.
Managing Code Snippets
Seeing the potential productivity gains with using snippets, several questions may cross your mind: Where are these snippets stored? Can I reorganize my snippets? How do I add my own snippets? Can I find more snippets on line?
The tool that can answer all of these questions is the Code Snippets Manager. The Code Snippets Manager, available from the Tools menu, provides a summary of each snippet, its shortcut, type, author, and location as shown in Figure 4.
![]() | ? |
Figure 4: The Code Snippets Manager helps you organize your snippets. |
For each language (Visual Basic, Visual C#, Visual J#, and XML), the Code Snippets Manager lists every snippet using the same folder hierarchy as the Code Snippet Picker. Select a snippet from within the folder hierarchy to see its details in the right pane.
To add a new folder to the folder hierarchy, use the Add button. To remove a folder and its contents from the folder hierarchy, use the Remove button. This allows you to reorganize your snippet folders as you desire.
To add a new snippet, navigate in the folder hierarchy to the desired folder and use the Import button to add a new snippet to that folder. This assumes, of course, that you already have a new snippet. More about this later. Use the Search Online button to search online for additional code snippets.
Using the Code Snippets Manager provides an easy way to see the code snippets that are available and to reorganize them as needed.
A Peek Inside Snippets
Let's take a peek inside a snippet to see how it is made. Then it will be an easy step to make our own snippets.
As shown in Figure 4, the Code Snippets Manager provides information on where each snippet is stored on your system. Let's take a look at the property procedure snippets used earlier in this article.
|
Navigate the folder hierarchy in the Code Snippets Manager to find the property procedure snippet. For Visual Basic, navigate to Common Code Patterns, choose Properties and Procedures, and then choose "Define a property." For Visual C#, use Visual C# and choose "prop." View the location of the snippet above the folder hierarchy.
Once you know the location of the snippet on your system, use Explorer to navigate to the snippet's directory and open the snippet. The property procedure snippet in Visual Basic is called DefineAProperty.snippet and is shown in Listing 1; in Visual C# it is called prop.snippet and is shown in Listing 2.
Notice that the snippet is actually XML (which should not be a surprise). The majority of the XML defines the snippet details such as its name, shortcut, and description. The key part of the XML file is the snippet itself.
In Visual Basic:
In C#:
The snippet uses the $ character to delimit the replacements in the snippet. The replacement can have any name, and using the same replacement name throughout the snippet provides for cascading edits.
You can edit the snippet files to modify the snippets. For example, if you would like to change the shortcut associated with a snippet, you can modify the snippet file Shortcut element.
Now that you know what a snippet file looks like, you can build your own snippets.
Building Your Own Snippet
To get the greatest benefit from snippets, you will want to create your own. There are several ways you can approach this task.
You can build your own snippets the hard way by manually creating the snippet file contents yourself with your XML editor of choice. But this means that you have to have an intimate understanding of the schema of the XML and have to do a lot of typing, typing, typing.
|
If you use the XML code window provided in Visual Studio 2005, you will get some assistance with creating your snippet. The XML code window Code Snippet Picker provides a Snippet snippet. This snippet provides you with the correct XML layout for a snippet XML file. All you need to do is tab through it to set the appropriate element values and then add the code you want for the snippet itself.
Another choice is to locate a snippet file that is similar to the snippet that you want to create. Copy the file, then edit it as you desire. This is the best choice if you simply want an enhanced version of one of the existing snippets.
By far the easiest way to create your own snippets is to use the open source Snippet Editor created by Bill McCarthy (Check out his blog), a developer from Australia and Microsoft MVP, in conjunction with Microsoft.
After downloading the Snippet Editor, launch the file SnippetEditor.exe. By default, the Snippet Editor displays Visual Basic snippets in a folder hierarchy in the left pane. Note that this is the same folder hierarchy as displayed in the Code Snippets Manager except that the snippet name is displayed instead of the title. To add snippets for other languages, use the Option button (on the far right of the toolbar) and select the desired language(s).
The Snippet Editor dialog allows you to edit existing snippets or create new ones. It allows you to add snippet folders and drag and drop snippets between the folders. It also allows you to build a Visual Studio Content Installer, making it easier to share your snippets with others. Most importantly, it allows you to search snippets by keyword using the filter feature just above the folder hierarchy.
For example, say you want to find any snippet having to do with properties. Type "prop" in the filter text box, click on the Apply button, and the folder hierarchy in the left pane of the Snippet Editor is filtered to only those snippets with the letters "prop."
Say you want to update the VB property snippet so that the private member variable is always prefixed with an underscore. Navigate the filtered folder hierarchy to the DefineAProperty snippet. Double-click on the snippet to edit it. It will then appear in the Snippet Editor as shown in Figure 5.
![]() | ? |
Figure 5: Create your own Visual Basic snippets using the VB Snippet Editor. Note that this is an open source project and the user interface may change. |
The Editor tab in the top right pane of the Snippet Editor allows you to edit the snippet as desired. The Preview tab provides a preview of what the code expansion will look like so you can confirm your expected results.
The bottom right pane of the Snippet Editor provides tabs to assist you with the editing of your snippet. The Properties tab displays the properties of the snippet such as the title, description, and shortcut.
The Replacement tab allows you to define the fields that are to be used as replacements when the snippet is expanded. You can add new replacements, modify existing replacements, or delete a replacement.
The References tab defines which references need to be added when the snippet is inserted into the code window. Similarly, the Import tab defines which imports need to be set.
Create your own snippet by right-clicking on the desired folder and selecting Add New Snippet from the context menu.
For example, say you want to create a specialized property procedure that knows how to handle object instances. Create your own snippet for this under common code patterns, choose properties and procedures, and name it InstanceProperty.
Double-click on the new InstanceProperty snippet to edit it. On the Properties tab, give the snippet a title, description, shortcut, and so on.
On the Replacements tab, add a replacement for the data type, private variable name, and property name. Then write the desired code in the Editor pane (or copy from one of the other snippets and edit it), using the replacements as needed.
Private $PrivateVariable$ As $PropertyType$ Public Property $PropertyName$() As $PropertyType$ Get If $PrivateVariable$ Is Nothing Then $PrivateVariable$ = New $PropertyType$ End If Return $PrivateVariable$ End Get Set(ByVal value As $PropertyType$) $PrivateVariable$ = value End Set End Property
Click on the Preview tab to confirm the results. When you obtain the desired results, save the snippet. The snippet is automatically added to the Code Snippet Manager in the defined folder. So it is immediately ready for your use in the code window.
Any time you find yourself typing the same set of code or looking up some syntax that you don't use very often, consider building a snippet for that code. As you build up your snippet library, you will have the code for many of your coding tasks right at your fingertips.
Try Out Snippets
Using snippets can provide a huge time savings, both in minimizing typing and in looking up syntax for commonly needed tasks.
Your snippets are yours. Modify them, reorganize them, and create your own so you can build a very efficient, personalized snippets library. And have fun!