Surround templates are used to quickly enclose an expression, a single statement, or an arbitrary block of code with if..else, try..catch or other code constructs. ReSharper intelligently reformats the code, adjusts the selection, and/or repositions the caret as specified by the template.
- In the code editor, select a block of code that you want to surround with a template.
- The actions list icon appears automatically to the left of the selected code block.
Press Alt+Enter or click on this icon and
choose the desired surround template from the actions list:
- Alternatively, choose ReSharper | Edit | Surround With Template, on the main menu or press Ctrl+Alt+J. In the Surround With menu, choose one of the predefined templates in the quick access list. If you want to use a custom surround template that was not added to quick access list, select More.
- If you have chosen More the Choose Template dialog box appears, where you can select a required template. To optionally introduce a template into the quick access list, select its entry in the Choose Template dialog box and select Add to quicklist in the lower part of the dialog box before clicking OK.
If the template is parameterized
(i.e. requires user input), the editor switches to the template editing mode and suggests an
for the first parameter.
You can type an appropriate value, choose one of the suggested values, if any,
or accept the default value suggested by ReSharper, and press:
- Tab or Enter to move to the input position of the next parameter.
- Shift+Tab to move the input focus to the previous input position.
- Esc to switch off the template editing mode and move the caret to the end position defined by template developer. In this case, all parameters will be initialized with default values.
Consider the following code fragment:
We would like to enclose the statement in a try..catch block to take care of possible System.IO.IOExceptions thrown. ReSharper conveniently offers the corresponding predefined template to streamline this operation.
Pressing Ctrl+Alt+J opens a drop-down list with available templates:
To choose the try..catch template, you can do one of the following:
- Click it with the mouse.
- Go down to the corresponding menu item and press Enter.
- Press 8.
We supply the desired exception type (IOException) at the first input field and press Tab or Enter to move on to the next parameter. At the second input position, we change the name of the exception variable suggested by ReSharper to ioExc, and press Tab or Enter again to quit the template editing mode. The caret and selection are moved to the positions specified by the template designer. The code in the editor now looks as follows:
Thus, if the basic exception handling code provided by ReSharper does not suit your needs, simply type your own catch block body in place of the suggested code.