Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Having Fun with Code Snippets

Using code snippets can make it quick to add common code pieces to your application, while creating your own snippets allows you to build a library of custom code pieces and share them with other developers.


advertisement
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.

 
Figure 1: Visual Basic provides a comprehensive set of task-based code snippets for your use.
 
Figure 2: C# focuses on code snippets for common language constructs.
 
Figure 3: XML code snippets provide easy access to XML syntax.
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);

Inserting snippets into your code is quick, easy AND saves you from all of that typing!
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.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap