This is a follow-up article to Lost Wonders of Visual Studio: Code Snippets. Code Snippets are like a beefed up version of IntelliSense, and allow you to quickly insert ready-made yet customizable code into your Visual Studio project. There are plenty of existing Code Snippets available, but there might not be one for your specific needs. If you ever wanted to create your own Code Snippets in Visual Studio, this is the tutorial to read.
To create a Code Snippet, you create a .snippet file that has a specific XML schema, and then import it into your Visual Studio user settings. Here are basic instructions to create your first Code Snippet, and to add common replacement elements for further customization.
Creating Code Snippets
- Create a file called MySnippet.snippet. Start with the Snippet XML Template in “References” below.
- Fill in all the TBD placeholders with the basic snippet information
- Title: Name of your snippet
- Author: Your name
- Description: Short description of your snippet
- HelpUrl: Reference URL
- ShortCut: Keyword to invoke your snippet
- Code Language: CSharp or VB
- CDATA: Enter your expanded code here.
- In Visual Studio go to Tools > Code Snippets Manager and click Import. Select MySnippet.snippet. It will validate the XML, then import your snippet. Click Finish.
- Now you should be able to invoke it using the shortcut keyword you provided.
- Add a Declarations element under the Snippet element. Use the format in the Declarations Element in “References” below.
- Fill in all the TBD placeholders:
- ID: Variable name for reference
- ToolTip: Help text to display while using
- Default: Default value
- You can also create an Object instead of a Literal. Use the same format as above, but add a Type element to specify the object type (for example: System.Data.SqlClient.SqlConnection).
- Repeat the Literal and Object blocks for any other replacements you need to include.
- Reference your replacements in your CDATA code expansion by referring to them as $ID$.
That’s just the basics. There’s way more you can do with Code Snippets. Things like:
- Adding assembly references (VB snippets only)
- Importing namespaces
- Snippets that surround code instead of just expanding
- Snippets that run during code refactoring
For more information, check out the MSDN Code Snippets Schema Reference.
[Snippet XML Template]
<?xml version="1.0" encoding="utf-8"?>