Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping multiple statements in braces

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.

like image 338
Matt Avatar asked Apr 05 '12 21:04

Matt


People also ask

Why do we use block of statements with braces?

Braces are used around all statements, even single statements, when they are part of a control structure, such as an if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.

Do you need brackets for if statements in C?

Opening and closing braces for if , for , and while statements should always be used even if the statement's body contains only a single statement.

Does a while loop need brackets?

Answer 52fd0cf97c82caea03000888. While loops continue looping “while” the condition in brackets is true. Since understand is true when the while loop gets executed, it loops through the code.

What are curly brackets used for in C#?

(about curly braces), in a nutshell, we use them to include all code between them in an if, loop, or any other compound statement. They're optional when you only wantto include one statement in the block.


1 Answers

Select rows of code.

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

Select option 7: { }.

Works for me.

like image 200
Phil Avatar answered Oct 27 '22 04:10

Phil