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.
When you press the tab key twice, youâ€™ll get this:
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:
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:
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:
When you select Insert Snippet, youâ€™ll see the new ones appear.
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:
This snippet expands to this:
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.
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.