Export (0) Print
Expand All

Code Snippets

A code snippet is a block of reusable code that you can insert where you need it in your code. Snippets can be simple or more complex—for example, blocks such as try-finally and if-else are commonly used, but you could also use snippets to insert entire classes or methods.

Visual Studio enables two kinds of code snippet: insertion snippets, which are added at a specified insertion point, and surround-with snippets (C# and C++ only), which are added around a selected block of code.

To insert an insertion snippet in your code, put the cursor where you want the snippet to appear, open the shortcut menu, choose Insert Snippet, and then navigate to the snippet you want, select it, and press the Tab key. If you already know the name of the snippet, just type its name at the cursor and then press Tab+Tab. For example, you could insert the following C# insertion snippet by typing tryf and pressing Tab+Tab, or by using the Insert Snippet command.

try
{

}
finally
{

}

To insert a surround-with snippet, highlight the code that you want to enclose, open the shortcut menu, choose Surround With, and then navigate to the snippet you want, select it, and press the Tab key. For example, to get the following C++ code, you could type return FALSE, highlight it, open the shortcut menu, choose Surround With, and then select if and press Tab.

if (true)
{
    return FALSE;
}
NoteNote

Some code snippets—for example, the C++ if snippet—can be used either as insertion snippets or as surround-with snippets.

Snippets can contain replacement parameters, which are placeholders that you must replace to fit the code you are writing. In the previous example, true is a replacement parameter, which you would replace with the appropriate value. That value is repeated for every instance of the replacement parameter in the snippet.

The following Visual Basic example shows a code snippet that inserts a property and contains replacement parameters. (To insert the snippet, open the shortcut menu, choose Insert Snippet, Code Patterns, Properties, Procedures, Events, and then select Define a Property and press Tab.)

Private newPropertyValue As String
Public Property NewProperty() As String
    Get
        Return newPropertyValue
    End Get
    Set(ByVal value As String)
        newPropertyValue = value
    End Set
End Property

If you change newPropertyValue to m_property, then every instance of newPropertyValue is changed. If you change String to Int in the property declaration, then the value in the set method is also changed.

To view information about the code snippets that are currently installed, choose Code Snippets Manager on the Tools menu and then select the programming language you want to examine.

In the Code Snippet Manager dialog box, you can also add or remove snippet directories, or import more snippets.

Show:
© 2014 Microsoft