Code Snippets in Visual Studio 2012
Welcome to Lost Wonders of Visual Studio, where we explore the strange and exciting features forgotten deep in the bowels of Visual Studio…
Code snippets were introduced in Visual Studio 2005 and documented in Visual Studio 2008… But then they largely disappeared from reference materials for Visual Studio after that. That being the case, if you’ve ever heard of this elusive creature you might be surprised to hear they are still alive and well in Visual Studio 2012!
What are Code Snippets?
A code snippet might sound like a cute pet (Here Snippet! Here boy!!) but it’s not. Basically, code snippets are like IntelliSense on crack. When you invoke one, it expands to an entire programming construct, not just a keyword. For example, in VB.NET (sorry C# folks, VB.NET’s just what I happen to be working in today) if you type “For” and press Shift-Tab, then Tab again, it will expand your “For” to:
For index = 1 To 10
Yeah I know, invoking it is a little goofy. Shift-Tab puts you in what I like to call “snippet-vision” (it’s kind of like Predator-vision) and subsequent Tab presses cycle through multiple available constructs, that is if there’s more than one available for that word.
Some snippets expand to many lines of detailed and complex code. For example, the one in the screenshot is a snippet called “Navigate using XPathNavigator” and it expands to:
Dim nav = xmlDoc.CreateNavigator()
Dim nodeIterator = nav.SelectChildren(XPathNodeType.Element)
‘ Interact with each child node here
What Code Snippets Are Available?
You can get a list of all the cute and cuddly code snippets in VS 2005 and up by pressing Ctrl-K, X. The browseable IntelliSense menu is pictured in the screenshot above, in its full glory. Snippets are even hierarchically categorized for easy access.
What About the Default Values?
You might be saying, hey those aren’t my variable names! Well, no worries. After you expand your snippet, simply press Tab to cycle through the variable and argument fields. This way you can quickly and easily replace the default placeholders with your very own variables and parameters.
A Snippet of My Very Own?!
I know they’re cute, but you can’t adopt one. Actually, yes you can!! You can make your very own snippets. I bet you’re squealing with delight! Unfortunately, it’s pretty ridiculous involved to get started, but it gets easier after you create your first one. It involves making an XML file with a .snippet extension where you define all the characteristics of your cute little snips. But that’s fodder for some future tutorial blog post…
I hope you enjoyed this edition of Lost Wonders of Visual Studio.
I’m your host, Ben Klopfer. Good night, and have a pleasant tomorrow.