Visual Studio Code for Mac developers: Code snippets

 

Visual Studio Code supports code snippets. This feature is very important at least for me because I use it during my presentations very often.

You can find that 0.8.0 Code preview version supports snippets for all common languages and if you want to create a new snippet, it’s better to start with User Snippets menu item

 

Alternatively, you can use Command Palette window to activate Snippets command.

Once you select User Snippets menu item, Code will offer to select language for which you create the snippet:

 

Select the language what you want, and Code will open the snippet template in Editor window.

 

The template is not very complex. You can see that it contains four main parts: name of the snippet; prefix, which you should use to activate the snippet; description; the snippet’s body, which contains the code itself.

Let’s look at the following code for our snippet:

 "Print to console": {
 "prefix": "prnt",
 "body": [
 "for (int ${i}=0;${i}<$1;${i}++)",
 "{",
 "Console.WriteLine(${i})",
 "}"
 ],
 "description": "Print to console"
 

This snippet can be activated using prnt keyword. It contains two parameters. The first parameter is a variable and the second one is a literal. You can see that in order to define literals we can use a dollar sign and a number but in order to specify a variable we can use brackets {}, dollar sign and variable name (or number). All variables/literals with the same name/number are connected. So you can specify name or value just once.

Open any C# file and click control+space (^Space) to activate snippets window:

 

You can see that for C# as well as for many other languages there are lots of predefined snippets.

Start typing prnt and select our snippet. Once code is inserted you can use Tab key to navigate between parameters.