Code snippets in Visual Studio are small parts of written code that can be inserted using a specific shortcut again and again in applications. In this post I will demonstrate how to use them through an example.
Suppose you find yourself writing the code below again and again in your application:
Then it is nice if you could create a snippet in visual studio and whenever you need this code, insert it automatically through a sequence of keyboard/mouse shortcuts.
To achieve this create an xml file called NewSnippet.snippet using your favorite text editor and add the following:
INSERT YOUR SNIPPET TITLE HERE
<Code Language="(SNIPPED'S CODE LANGUAGE, EG:CSharp)">
INSERT YOUR CODE HERE
Where in the "INSERT CODE HERE" section you put the previous code that you want automatically generated.
Save this file and within Visual Studio under Tools/Code Snippet Manager you can "Import" the snippet to the desired folder (in this dialog you can actually do more than that in terms of organizing your snippets).
After importing your snippet you can press the shortkut Ctrl+K+X in your code and have your snippet inserted.
This is half of the power. The other half comes from the fact that you can insert placeholders in your snippet for specific words in the snippet's code that should be changed according to the context the snippet is inserted. For example you want the following code in a snippet:
private String TestMe="";
if (TestMe=="") //Do Something;
But whenever you use it the property type should be different as well as with the property name and the initializer.
You can tell in your snippet where the user should be prompted to enter a value and where this value should be entered. The snippet's code for this is as follows (note the declaration section and its use within the code and the correspondence between the ID for each declaration and the enclosed IDnames in $ signs within the snippet's code):
<ToolTip>Put initialization here.</ToolTip>
<ToolTip>Put property name.</ToolTip>
<ToolTip>Replace with the desired type.</ToolTip>
private $PropertyType$ $PropertyName$=$InitializationValue$;
if ($PropertyName$==$InitializationValue$) //Do Something;
The following if imported as snippet in Visual Studio appears with Ctrl+K+X and as soon as it appears we can use the Tab key to naigate in the snippet's paramters and set their values accordingly.