Code Snippets Gone Wild

One of my favorite new features in Visual Studio 2005 is the code snippets technology. Let’s face it. One of the reasons some of us (the names will not be given in order to protect the guilty), used fields instead of properties in our classes because we just didn’t want to type those extra lines of code. I used to use a product called Code Rush with Visual Studio 2003, but it seemed like a lot to learn and sort of seem to get in the way at times.

Visual Studio 2005 comes with a neat feature called “code snippets,” which fills in a section of code for you and lets you modify certain fields by just tabbing through and typing. Take, for example, a foreach loop. When you type foreach in the code editor, you’ll notice a foreach item in the intellisense drop down.

 foreach 1

When you press the tab key twice, you’ll get this:

foreach 2

Then, simply type to replace the highlighted item, and press tab to go to the next item. Eventually, you’ll end up with something like this:

foreach 3

It’s no secret that VB develops have a heck of a lot more snippets out of the (virtual) box than do C$ developers. Well, the MSDN team has come to the rescue and posted the equivalent snippets for C#.

After installing them, follow the instructions here to add them to your VS IDE. If you don’t see the “Code Snippets Manager” item on the Tools menu, just right-click the toolbar and click Customize. Then select it from the dialog, like so:

Code Snippets Manager

After opening the Code Snippets Manager from the Tools menu, click the Add button and navigate to the folder where you installed the new snippets. When you right click in a class or method, you’ll see the following context menu:

Insert Snippet 1

When you select Insert Snippet, you’ll see the new ones appear.

Insert Snippet 2

Alternatively, you can just press Ctrl+Spacebar in your code, and the new snippets will appear in the list, right along the old ones like foreach. Here’s one for changing the fore and back color of text in a Console app:

Insert Snippet 3

This snippet expands to this:

Insert Snippet 4

Of course, the problem now is that there are a TON of snippets to learn. Again, the Code Snippet Manager comes to the rescue, allowing you to examine each code snippet to see what it does.

Snippet Help

The best part of it all is that snippets are a great way to learn how to perform common tasks. Whenever I press F1 in Visual Studio, I usually just scan the text and go right to the code example to see how something works. Snippets can offer the same service, all from within the IDE.

Have fun!

About Tony Sneed

Sr. Software Solutions Architect, Hilti Global Application Software
This entry was posted in Technical. Bookmark the permalink.