What is a Code Snippet
A code snippet is a small chunk of reusable code which is used in development and inserted in the code file using the context menu or some combination of the hotkeys and a specified keyword.
Example
If-else block tries to catch or auto implement it property, we add it through the context, as well as some combination of hotkeys or the keywords.
There are 2 types of snippets
- Expansion Snippet
This is added at the particular insertion point. For instance, if we want to add the if block, we type if and press the tab so the if keyword is expanded to the if(true){ } block, then this is inserted by the keyword if and by using the context menu.
Example
Type if and press tab and you get the if block; if you type tryf we get the try { } finally {} ; and if we type class and press tab we get the class declaration
- Surrounded-With Snippet
It surrounds the specific chunk of code “like in array index print”, we surrounded it with the for loop, which surrounded the snippet as we type.
Return x; select the return x and then right click. Click on the surrounded snippet and then pick the desired snippet.
Step 1
- Open VS and go to Code Snippet Manager.
- We get the dialogue, which lists the snippet, according to the frameworks.
- Select the framework for which you want to make the snippet.
- In my case, I want to make any custom snippet for C# language.
- Select Visual C# to expand it, which contains all the snippets provided by the Visual Studio.
- Copy the path; we want to open that snippet and after that, we make it our own snippet.
- Go to file menu, click open and click the file.
- Open the snippet that is the snippet of the if statement written in the XML and save with the .snippet. Hit Ctrl+A and Ctrl+C.
- Title - Title of the snippet which you want to give
- Shortcut - Shortcut code which you type and then press the TABand the snippet is inserted
- Description - Little bit of description about the Snippet
- Author - Author of the snippet
- SnippetType - Two Types of Snippet
- Code section - Here is the code which we treat as the Snippet we chose; language like cSharp,VB etc.
Step 2
- SqlConnection Con=newSqlConnection("XYZ");
- SqlCommand cmd=newSqlCommand("XYZ",Con);
- cmd.Parameters.AddWithValue("XYZ", 2.ToString());
- Con.Open();
- cmd.ExecuteNonQuery();
- Con.Close();
All the work is done and it's the time to check the snippet.
Open any VS Project type “SQL”, press tab two times, and you will get the snippet.
Press the tab two times.
Conclusions
This is the complete tutorial to make the code snippet in Visual Studio. The code snippet rapidly enhances the productivity of the developer. I am enjoying the valuable feature of Visual Studio.