This article is all about creating and implementing Code Snippets using Visual Studio 2010.
What is Code Snippet?
A Code Snippet is a block of code which can be reused again and again without writing an entire block.
Consider we are in a presentation and about to show a demo, so we can't write all the code now. One thing we can do is we can keep our coding ready prior to the presentation but what if we want to write everything live.
We need some kind of trick for faster development. And Code Snippets are useful here.
What we will do is to:
- create our code
- convert it to a snippet
- assign a shortcut
How to create?
Let's create a sample snippet for adding two numbers accepted from the user by the Console.ReadLine() Method.
1. Create a XML File addnumbers.snippet.
2. Now the Code Snippet can have two sections Header and Snippet.
The Header section contains information about the snippet, like what is the shortcut, description, title, author etc. Whereas the Snippet Section defines how the snippet will be rendered and it has two more sub sections Declarations and Code.
3. Define the Header section as:
4. Define the Declaration sub-section in the snippet section as:
5. Define the Code sub-section in the Snippet section as:
- The Declaration section explains variable (written as $Variable$) in the code section.
- Make a practice to place all similar snippet files in a single folder.
Ex: put all math snippets in a single folder.
How to use snippets?
Click on add and select the folder. That's it! Now just type the shortcut you have provided and press tab twice. A couple of days ago, I uploaded a reusable data access layer. You can download it from here:
The good news is that now snippets are available for it, see:
Database coding is much easier now.