How to make custom code snippet in Visual Studio
Posted On Sunday, September 6, 2009 at at 9:19 PM by test
A cool feature that Visual Studio has is the concept of a "code snippet." You know those chunks of code that you need to type over and over again throughout your code? Perhaps your logging calls, or even more mundane than that, the generic code for try-catch blocks. Well, the folks behind Visual Studio came up with an idea to help keep that concept to a minimum - code snippets. Essentially, it is like having that repetitive code always on your clipboard, ready to "paste" into your code - except it is way more powerful than just copying and pasting code.
If you have used Visual Studio for a while, you have probably run across some of the standard code snippets - you may even be using them intentionally all the time. Today we are going to look at first how to use snippets in your code (really easy to do), and then we are going to take a look at how you can write your own code snippets. It is in writing your own code snippets that you really start to see the power of the code snippet system, and hopefully after today's tutorial you can go off and streamline your own work flow by writing a couple snippets for yourself.
So first, lets take a look at adding existing snippets to code. There are a number of ways to do this in Visual Studio, the most common of which is to use regular intellisense. For instance, below we are about to add a for
loop snippet:
You can also get to a menu of just snippets by using the right click menu and choosing the option "Insert Snippet". And, of course, if the mouse is too much work for you, there is a keyboard shortcut that will bring up this menu directly - ctrl-k + ctrl-x. Below, you can see the menu in action as we choose again to insert the for
loop snippet.
You might be wondering "why would I want to use a for loop snippet?" - cause after all, a for loop it really isn't that complex to write. Well, what it does is give you the full for loop framework with only a couple keystrokes. This is what inserting the for loop snippet will give you:
If your not convinced that saved you that many keystrokes, theres another handy feature. See how the first "i" is highlighted and the second two are surrounded by dotted lines? That means that those variables are supposed to be the same - which mean that if you edit the first "i" right after you insert the code snippet, the other "i"s change to the new name automatically. That 'linkage' isn't kept around forever, as soon as you go and edit something other than the snippet, those dotted lines go away and any changes that you make later on don't automatically get propagated. But pretty cool, eh?
Another handy feature of snippets, is that for many of them you not only have the ability to "insert" them, you also have the ability to surround other code with them. For instance, if you had highlighted some code, done a right click, you can pick "Surround With.." from that right click menu (it is right below "Insert Snippet" in the right click menu pictured above). Then, only the code snippets that can do a "surround" operation will appear, and you can pick one and add it. And surround does exactly what you might expect - for instance, in the case of the for loop, it will surround the code you had highlighted with the for loop structure pictured above. The keyboard shortcut for this "Surround With" action is ctrl-k + ctrl-s.
Ok, enough on using code snippets - lets try and write one! For this tutorial, we are going to create a really simple snippet for performance timing. It will work as both an "insert" and "surround" code snippet, and this will be the code that it produces:
All it does is surround a block of code with a line at the start that captures the start time, and a line at the end that prints out the difference between the start time and the current time. There are two blocks that are set as editable - first, the name of the startTime
variable (which will also change the startTime
reference at the end of the snippet), and the "My function" part of the string, so that you can put a more descriptive name of exactly what you are timing.
So how do we do this? Well, all a code snippet is is an xml file - and a relatively simple one at that. Here is the basic outline of a code snippet xml file:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
</Header>
<Snippet>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Pretty standard initial xml declaration stuff. There is a CodeSnippets
block that can contain one or more CodeSnippet
blocks. Each CodeSnippet
block has a Header
block (for stuff like title and author) and a Snippet
block (for the actual snippet code). Below is an example Header
block:
<Header>
<Title>Simple Performance Timing</Title>
<Shortcut>Timing</Shortcut>
<Description>
Code snippet for surrounding a section of code with
some performance timing.
</Description>
<Author>Switch On The Code</Author>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
Nothing crazy here - we give the snippet a title, a shortcut (which is what shows up in all the intellisense menus), a description and an author. With the SnippetTypes
block, you declare what type(s) this snippet supports - in this case, it can do both "SurroundsWith" and "Expansion" (i.e., insertion). So onto the actual definition of the snippet:
<Snippet>
<Declarations>
<Literal>
<ID>startTime</ID>
<ToolTip>Beginning Time Variable</ToolTip>
<Default>startTime</Default>
</Literal>
<Literal>
<ID>message</ID>
<ToolTip>Replace This With Your Description</ToolTip>
<Default>My function</Default>
</Literal>
<Literal Editable="false">
<ID>DiagnosticsDebug</ID>
<Function>
SimpleTypeName(global::System.Diagnostics.Debug)
</Function>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[
long $startTime$ = Environment.TickCount;
$selected$ $end$
$DiagnosticsDebug$.WriteLine(String.Format(
"$message$ took {0} ticks.", Environment.TickCount - $startTime$));
]]>
</Code>
</Snippet>
There are two main sections here, Declarations
and Code
. It is in the declarations that we can declare the special variables that appear in multiple places in the code (like startTime
), or variables that just need to be edited when the snippet appears (like the "My function" string). As you can see, the first literal that we declare is startTime
- we give it a name to refer to it as in the snippet (in this case "startTime"), a tool tip that will appear for the user describing what the variable is, and a default value. We can then use this literal down inside the code snippet itself - refering to it as $startTime$
.
The next literal is just as simple - it is the placeholder for the "My function" string, and we call it message
. You can see it down in the code in the output string refered to as $message$
. The third literal is kind of weird. It is not editable by the user (declared by the Editable="false"
attribute), and it has a Function
tag. What this allows us to do is have the snippet figure out automatically if it should output the code using the full reference System.Diagnostics.Debug
or just the shorthand Debug
. If already have a using System.Diagnostics;
statement in your code, then there is no need for the full declaration, and the snippet realizes this. The work is actually done in that SimpleTypeName
function in the Function
tag. You can read more about this and the other available functions for use in snippets in the MSDN docs.
And that brings us down to the actual code inside the Code
tag. Most of this is the actual code that will appear after insertion, and we already explained what $startTime$
and $message$
. There are two other oddities here - $selected$
and $end$
. They are both reserved identifiers in code snippets - $selected
represents whatever the user had highlighted when they decided to do a "Surround With" snippet, and $end$
signifies where the caret should go after the user finishes inserting the snippet.
And that is about it for defining a code snippet. There are, of course, a number of other optional attributes/tags that we did not hit on with this simple snippet, but the MSDN docs do a pretty good job of explaining them. Below is the entire timing code snippet as a single block:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Simple Performance Timing</Title>
<Shortcut>Timing</Shortcut>
<Description>
Code snippet for surrounding a section of code
with some performance timing.
</Description>
<Author>Switch On The Code</Author>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>startTime</ID>
<ToolTip>Beginning Time Variable</ToolTip>
<Default>startTime</Default>
<Type>long</Type>
</Literal>
<Literal>
<ID>message</ID>
<ToolTip>Replace This With Your Description</ToolTip>
<Default>My function</Default>
</Literal>
<Literal Editable="false">
<ID>DiagnosticsDebug</ID>
<Function>
SimpleTypeName(global::System.Diagnostics.Debug)
</Function>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[
long $startTime$ = Environment.TickCount;
$selected$ $end$
$DiagnosticsDebug$.WriteLine(String.Format(
"$message$ took {0} ticks.", Environment.TickCount - $startTime$));
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
But wait! You might be wondering how you actually add a code snippet for Visual Studio to use after you have created it. You will want to go up to the Tools menu and choose Code Snippets Manager:
Once you click on that, you get the Code Snippets Manager dialog:
And from here it is pretty self explanatory - you can import snippet files (using the aptly named "Import" button), or you can add a folder's worth (in which case, as you add and remove snippets from that folder, they will appear/disappear from the available snippets).
I hope you've enjoyed this introduction to Visual Studio snippets. There are a number of resources out there for finding code snippets that other people have written, such as Got Code Snippets. If you have any questions about writing your own snippets, or cool uses for them, please leave a comment.
Thats great article regarding the snippets, can you please post little more about VS2010. I appreciate your sharing information.
Dear Author aspnetcsharp4.blogspot.com !
I can not participate now in discussion - it is very occupied. I will return - I will necessarily express the opinion.
l0c18q3l26 q4s20q9y26 s5h60r9y15 d5c42g5l51 v5e20j0q11 r8r41i5o65