This post gives introduces code snippets in Visual Studio, how you can use them and helps you find out the list of built-in code snippets for each language easily. Code snippets in Visual Studio are useful in reducing typing effort required to input code. Code Snippets help in several ways to simplify your work if you can remember to use them instead of typing the actual code. Code Snippets are present in Visual Studio from ver 2005.
To use code snippets, instead of typing the code you will type a shortcut, which actually is a word and press Tab key to insert the actual code to which the shortcut is linked with.
For example, to enter the below code..
for (int i = 0; i < length; i++)
You can type "for" and then press Tab, you will then get the code inserted into the code window as shown below..
Now you can see that “i” is highlighted, this means you can type a name for the loop variable, once you renamed it, you can press Tab to select “length” and rename it or specify what should be there, like, list.Count, etc. Once done, press enter to place the cursor inside the for loop braces.
As you can see, whenever you need to write a for loop you can just use this code snippet and save time, there are many code snippets like this which you can use.
Also, you can right click in the code editor and select Insert Snippet...(Ctrl+K, X) and choose the snippet you need from the list. You can also select lines of code and right click and select Surround With...(Ctrl+K, S) option to put the selected code into the snippet that you will insert, like, inside a try..catch block.
Code snippets are actually customizable as like most Visual Studio features. A code snippet is loaded from a “.snippet” file and the below image shows the location of the built-in C# code snippets. You can find snippets for VB & other languages in the language specific folder.
(C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#)
I will write a future post on how to create your own code snippet for frequently entered common code patterns in your project and how to distribute them within your team so that everyone can use them.