Code Snippets are the little shortcuts in Visual Studio that help us do boilerplate stuff faster. For example in a C# class file, if we write prop and hit Tab, a property gets generated allowing us to change the Type and Name of the property.
Of late, I have been blogging a lot and most examples involve some amount of boilerplate code that get’s repeated. For example if you are doing Poor Man’s DI, the code for the Controller Factory and Composition Root are very similar. If we could have a code snippet that could drop in the code and let us modify the variables etc. it would save a lot of time.
Visual Studio has had code snippets since I can remember. But building a code-snippet involved knowing the exact XML format, hand coding the xml, deploying it, etc. etc. Enter ‘Snippet Designer’ a Visual Studio extension that helps you create and deploy snippets easily. Snippet Designer is available on CodePlex at http://snippetdesigner.codeplex.com/
Step 1: Install ‘Snippet Designer’ Visual Studio extension through the plugin manager. Once installed, creating snippets are a breeze.
Step 2: Write the code. Select the code, right click on it and select ‘Create Snippet’.
Step 3: Now select the keyword that you want to be replaceable, right click on it and select Make Replacement.
The word will get highlighted and surrounded by $’s. Select all the keywords you want replaceable.
Step 4: You can change the ID and the Tooltip in the Replacement grid at the bottom
Step 5: Once you are done, update the ‘Shortcut’ property for the snippet in the Property Window. This is the value you see in the code autocomplete.
Step 6: Save the Code Snippet, by default it goes under C:\Users\<UserName>\Documents\Visual Studio 2010\Code Snippets\Visual C#\My Code Snippets folder
Step 7: Add a new empty class file and type in the shortcut
Once the correct shortcut appears, hit Tab to expand the complete code snippet and you can Tab through the Replacements that you had setup.
That’s how easy it is to convert code to snippet using Visual Studio snippet designer.
Snippet Designer also has a Snippet Explorer that you can access using the View > Other Windows > Snippet Explorer. You can view all the snippets available to you in it. Just remember the search is case sensitive.
You can create code snippets for important presentations or creating boilerplate code. Have fun!
Tweet
No comments:
Post a Comment