ReSharper, day 4: Auto closing delimiters

Welcome to day 4 of my 31 Days of ReSharper.

Here’s a feature you’ll notice as soon as you start typing: when you type an opening delimiter, ReSharper will type the closing one for you.

It’s a simple feature, but not a simple one to do well, and except for a bug that they introduced in 2.5 (and then fixed in 2.5.1), they do it well. Very seldom does it do the Wrong Thing.

This works for the following delimiters: {, (, [, ", and '. It doesn’t autocomplete generic syntax, though: < is not on the list.

Here’s a sample of it at work.

Starting out with an empty statement.
You type a method name…
and type “(“.
You type a subexpression…
and type “(“.
Oops. You meant “[“, not “(“. Backspace…
and type “[“.
Once you’ve typed the parameter…
you type “]”…
then you type “)”…
and then you type “;”.

They do the things right that need doing right: when you backspace over an opening delimiter, they remove the closing delimiter (assuming you didn’t type anything inside the parens yet); and when your cursor is before the closing delimiter and you type the closing delimiter, you don’t end up with two. This also applies to semicolons; when the cursor is before a semicolon, you can type a semicolon, and you won’t get two. You can just type normally, without having to hit the right arrow all the time.

They’re even smart enough to make it work inside arbitrary nesting: if you type the opening delimiter and the closing delimiter is already there, they don’t add it. There’s got to be some guesswork involved at some point, but I don’t remember it being wrong enough to notice.

Note: When you type {, you automatically get the matching } — meaning, if your intent is to put braces around a block of code, the matching delimiter gets in your way. Instead, you can use Surround With to add the braces around the current selection. The shortcut for adding braces is Ctrl+Alt+J 8. (Ctrl+Alt+J pops up a menu, so you don’t need to memorize the “8” part.)

(Update: Ilya, one of the ReSharper developers, notes that you can have ReSharper add the closing brace when you hit Enter, instead of right away, which would make it easier to simply type braces around a block of existing code. Thanks, Ilya!)

Leave a Reply

Your email address will not be published. Required fields are marked *