Monday, 19 September 2011

How to create your own custom code snippets in Visual Studio

If you are a developer and do lots of programming then Most of the time code lines get repeated. So you have to write them again and again or if you do copy paste then every time you have to change the name and ID’s or whatever is to be changed for readability. Visual Studio facilitates you to create you own custom code snippets for such situations. There are already such snippets comes and get installed with visual studio.

image Snippet Symbol that appears in Intellisense window.

for e.g. in C# we have snippet like below:

ctor – for default class constructor

for – for default for loop snippet

svm – for main function

prop – to create property

etc. So what you do is just type these words and double tap on TAB key and code get generated there just like that. This is one of feature that I love in our VisualStudio.

I suggest you a must have tool that you want to use and surely will love it. The Snippet Designer for VisualStudio. you can also write your own code snippet.

Download the addin from here:

Snippet designer for Visual Studio 2010/2008

Install the plugin Restart your VisualStudio. Now follow below steps:

Go to Menu File-> New –> File.. option


you’ll see a new template installed there for Snippet Designer


Select the CodeSnippet file template and click ok.

Now mention the name of SnippetName [it’ll appear as the tooltip when you use this snippet in your code] and select you language for which you want to create the snippet.


Now start typing you code or just copy paste it from you source. Now its time to choose the Literals you may want to change by your own at the time use. Wrap the string with $ It’ll automatically replace all the occurrences of that string in your snippet. See the snapshot below:


Now you are almost done here. Now Go to properties window and mention a shortcut that’ll let this snippet appear


Now save the file by pressing Ctrl + S and select a location to save this snippet file.


Now Open a new project and start typing the shortcut key you mentioned.


You custom code snippet will appear now double Tap the TAB key


Now change the values of the literal you have want to as per your choice.

and you are done Smile . I hope next time you go for some demo or something you might want to create some Snippets like this so that you don’t have to type your code again and again and by just pressing few keys and your code will appear just like that. Impress your audience or your colleagues.

Be a Smart Programmer.