Visual Studio 2008 Code Snippet Technology

Visual Studio 2008 (as well as Visual Basic 2008 Express) also has the capability to insert complex blocks of VB 2008 code using menu selections, context-sensitive mouse clicks, and/or keyboard shortcuts using code snippets. Simply put, a code snippet is a predefined block of Visual Basic 2008 code that will expand within the active code file. As you would guess, code snippets can greatly help increase productivity given that the tool will generate the necessary code statements (rather than us!).

To see this functionality firsthand, right-click a blank line within your Main() method and activate the Insert Snippet menu. From here, you will see that related code snippets are grouped under a specific category (Code Patterns, Data, Windows Forms Application, etc.). For this example, select the fundamentals >- math category and then activate the Calculate a Monthly Payment on a Loan snippet (see Figure 2-14).

Once you select a given snippet, you will find the related code is expanded automatically (press the Esc key to dismiss the pop-up menu). Many predefined code snippets identify specific "placeholders" for custom content. For example, once you activate the Calculate a Monthly Payment on a Loan snippet, you will find three regions are highlighted within the code window. Using the Tab key, you are able to cycle through each selection to modify the code as you see fit (see Figure 2-15).

Figure 2-14. Inserting VB 2008 code snippets
Figure 2-15. The inserted snippet

As you can see, Visual Studio 2008 defines a good number of code snippets. To be sure, the best way to learn about each possibility is simply through experimentation. Under the hood, each code snippet is defined within an XML document (taking a *.snippet extension by default) located under the C:\Program Files\Microsoft Visual Studio 9.0\VB\Snippets\1033 directory. In fact, given that each snippet is simply an XML description of the code to be inserted within the IDE, it is very simple to build custom code snippets.

Note Details of how to build custom snippets can be found in my article "Investigating Code Snippet Technology" at While the article illustrates building C# code snippets, you can very easily build VB 2008 snippets by authoring VB 2008 code (rather than C# code) within the snippet's CDATA section.

Was this article helpful?

0 0

Post a comment