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

  1. Create a file called MySnippet.snippet. Start with the Snippet XML Template in “References” below.
  2. 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.
  3. 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.
  4. Now you should be able to invoke it using the shortcut keyword you provided.


Literal Replacements

  1. Add a Declarations element under the Snippet element. Use the format in the Declarations Element in “References” below.
  2. Fill in all the TBD placeholders:
    • ID: Variable name for reference
    • ToolTip: Help text to display while using
    • Default: Default value
  3. 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).
  4. Repeat the Literal and Object blocks for any other replacements you need to include.
  5. Reference your replacements in your CDATA code expansion by referring to them as $ID$.


Advanced Topics

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]


[Declarations Element]


Like this post? Share it!