Click here to Skip to main content
15,884,388 members
Articles / Programming Languages / C#
Tip/Trick

Creating and Using Code Snippets in Visual Studio

Rate me:
Please Sign up or sign in to vote.
3.75/5 (13 votes)
13 May 2015CPOL4 min read 35.1K   14   6
The easiest way to create and use code snippets in Visual Studio

Creating Snippets Spodee-O-Dee

We have all written boilerplate code, sometimes ending up copying-and-pasting it -- but looking over our shoulder before doing so, because "Copying-and-Pasting Code Considered Harmful". Or, we simply (albeit laboriously and tediously) typed in the code afresh each time it was needed because the boilerplate code was not at hand.

Probably every Visual Studio user knows about code snippets, and may even remember to use them from time to time (for properties, foreach loops, etc.) However, what about creating our own? We may think it will take too long and thus simply revert to our old copying-and-pasting or sighing-and-typing ways rather than invest that time up front.

It does take a little time to write code snippets and then incorporate them into Visual Studio but, when using the Snippet Designer extension, the emphasis is on little. It literally only takes a couple of minutes. From then on, adding your custom code snippets is as easy as mashing ("to mash" is Southern (Southern as in Georgia, Alabama, Lousiana, etc., not Southern as in Argentina, Chile, etc.) for "press"/"push"/"enter"/"key in", etc.) Ctrl+K, X and selecting the required snippet. So without further ado, adon't, or Mountain Dew (either type), here are the steps:

Download and Install the "Snippet Designer" Visual Studio extension. Do so by selecting Tools > Extension Manager... and then selecting "Online Gallery" and searching for that ("Snippet Designer")

After the Snippet Designer has been installed, enter the boilerplate code you want to reuse later in a Visual Studio *.cs file (you are using C#, aren't you? If not, march right up to a mirror, peer into it, and slap the first person that shows up). For example, I entered this:

C#
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell1 = new HtmlTableCell();
HtmlTableCell cell2 = new HtmlTableCell();
HtmlTableCell cell3 = new HtmlTableCell();
row.Cells.Add(cell1);
row.Cells.Add(cell2);
row.Cells.Add(cell3);

Now highlight the code you added, right-click, and from the context menu select "Export as Snippet" (this context menu item was added by the Snippet Designer extension/add-in/plugin).

This will open a snippet designing tab within Visual Studio that looks like this:

Snippet File in VS Designer

First, change the name from the default "SnippetFile1" (or similar) to something more descriptive of this specific snippet - that's how it will appear in Visual Studio when you go to insert the snippet, too, so "SnippetFile1" or some such is not going to cut the mustard, at least not with a sufficiently sharpened scythe.

Then, add (not strictly necessary, but for egocentric or possibly even megalomaniacal purposes - or for legal reasons (one can never be too careful!)) a value to the "Author" property. Also, I add a Description of what the Snippet is, and a Shortcut.

If your snippet is not straight boilerplate - that is to say, if you will change at least some of the instance names - highlight in turn each instance name you will want to change after inserting the snippet, right-click, and select 'Make Replacement' from the context menu. This will add some values to the next empty row in the "Replacements" section at the bottom of the snippet designing window. If you want to, you can change these values as needed.

I did not change any of the values in the 'Replacements' grid, but I did add "replacements" for "row", "cell1", "cell2", and "cell3" because if I add this snippet more than once within a method, the instance names will have to differ from each other. After 'making' those 'Replacements', the snippet designer now appears like so:

Snippet Designer in VS Designer following modifications

Now, to save your praiseworthy and perspiration-inducing work, right-click on the snippet tab and select "Save [whatever you named it].snippet" That will allow you to change the name to something sensible, and save it in a good spot:

Saving the Snippet

I saved this snippet as "RowWith3Cells".

Now to use the snippet in Visual Studio, mash Ctrl+K, X and select "My Code Snippets", then "RowWith3Cells". You should see something like this:

On the verge of inserting the Snippet

The snippet you created is plopped right down into your code, as cozy as a grizzly bear or bearess in his or her hibernatorium in late December (and almost as docile). You can then change the "Replacement" value declarations to whatever you want, and they will be changed throughout the snippet where they are thereafter referenced. And that's it - pretty easy, if you use the Snippet Designer. You no longer have any excuse to eschew creating Code Snippets, because not to do so would be penny wise and pound foolish or, to state it more directly, minutes wise and hours foolish.

Caveat Lector / Caveat Programor

This works for me in Visual Studio 2010. I have not tested it in other versions of Visual Studio, either newer or older. I assume it will work in newer versions, but I wouldn't bet the farm (or even my booty) on older ones. Hopefully, you're not stuck having to use an older version of Visual Studio than 2010, but if you are, feel free to buy yourself a beer and make it salty the organic way. Note: A (gentle?) reader wrote that it worked for him in VS 2013.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
PraiseGreat Pin
Franco Rosatti12-Jul-17 9:37
Franco Rosatti12-Jul-17 9:37 
GeneralMy vote of 5 Pin
Gaston Verelst16-May-15 7:05
Gaston Verelst16-May-15 7:05 
I always forget that I can create my own code snippets, so now I'll start.
Thanks for the nice explanation!
QuestionNice Tip* Pin
DaveMathews14-May-15 2:38
DaveMathews14-May-15 2:38 
QuestionMy vote of #1 Pin
BillWoodruff13-May-15 20:26
professionalBillWoodruff13-May-15 20:26 
AnswerRe: My vote of #1 Pin
B. Clay Shannon14-May-15 2:09
professionalB. Clay Shannon14-May-15 2:09 
GeneralMy vote of 5 Pin
VICK13-May-15 18:46
professional VICK13-May-15 18:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.