Wrapping multiple statements in braces

Go To StackoverFlow.com

18

Is there a keyboard shortcut in Visual Studio 2010 (I'm using ReSharper 6.1 also) that will allow me to surround a selected block of text with curly braces? I tried "Surround With..." (Ctrl+K, Ctrl+S), but I didn't see an option in the list to choose curly braces as the surrounding element. The common use case for this is that I'll have an if-statement like the following:

if (conditional)
    statement1;
// the rest of the program

I'll realize that there are some additional tasks that need to be performed inside the if-statement and I add them:

if (conditional)
    statement1;
    statement2;
    statement3;
// the rest of the program

Then, I remember that I need to wrap all the statements in curly braces and the code should really look like this:

if (conditional)
{
    statement1;
    statement2;
    statement3;
}
// the rest of the program

What I'd like to do is just select the three statements and then hit a shortcut key to wrap them in curly braces. What I actually end up doing is moving the cursor to the beginning of the line after the conditional, then typing a { character, then deleting the } character that ReSharper (unhelpfully) automatically inserts immediately after the {, then moving the cursor down to end of the last statement of the block and entering } to complete the block.

2012-04-05 21:42
by Matt
I don't think this can be done, the closes I've got is hitting a curly brace and shifting the code into the block manually, but I am guessing this is not what you want.. if it can be done i'd be interested - krystan honour 2012-04-05 21:47


25

Select rows of code.

Press Ctrl E-U (Surround with template) (or Ctrl Alt J for Intelli J).

Select option 7: { }.

Works for me.

2012-04-05 21:54
by Phil
Ctrl E-U didn't work for me, but that may be because I have it mapped to something else. However, I'm giving you credit because SurroundWith actually is the right answer. The problem turned out to be that my keyboard shortcut was associated with the Visual Studio version of SurroundWith, not the ReSharper extension. Once I went into Tools->Options->Keyboard and set a keyboard shortcut for ReSharper.ReSharper_SurroundWith and removed the shortcut from the default Edit.SurroundWith, it worked - Matt 2012-04-05 22:15
Ads