FEATURES
Code snippets are custom pre-defined templates that make it easier to enter repeating code patterns, such as loops or conditional-statements. Visual Studio Code provides the feature to create recurrent models.
This article covers the following topics.
- How to create a code snippet?
- How to assign keyboard shortcuts to code snippets?
Prerequisites
- Download visual studio code if not installed earlier. Link
- Install a C# extension from the visual studio code marketplace.
Getting Started
Easily enable snippets using visual studio code to avoid writing repetitive code.
Snippets are written in JSON and support C style comments. The editor allows adding any number of snippets and configures the language-specific snippets as well as general snippets used across the editor.
Snippets Path
For Windows
File > Preferences > Select User Snippets
Mac OS
Code > Preferences > Select User Snippets
How to create a code snippet?
For a demonstration, take an example of a basic code snippet that inserts Console.WriteLine statement in the C# files.
JSON code: Snippet accessed using the prefix name in the C# file.
"Print to console": {
"prefix": "log",
"body": [
"Console.WriteLine('');"
],
"description": "Log output to console"
}
Follow Live Instructions
![](https://cdn-images-1.medium.com/max/2560/1*n22diY1Am-T1GnVurlBwbw.gif)
How to assign keyboard shortcuts to code snippets?
Visual Studio Code allows us to assign a keyboard shortcut keys to code snippets.
Do NOT assign any reserved shortcuts because code snippets key mapping will override the existing default shortcut keys.
For a demonstration, take an example of a basic code snippet that inserts Console.WriteLine statement in the C# files and with a shortcut key i.e., “Ctrl+l.”
JSON Code
{
"key": "Ctrl+l",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "Console.WriteLine()"
}
}
Follow Live Instructions
![](https://cdn-images-1.medium.com/max/2560/1*yMm7v0LCtIV5wZUiEdfj1w.gif)
Thank you for reading. Keep visiting and share this in your network. Please put your thoughts and feedback in the comments section.