Visual Studio 2015 How to quickly move existing code after an expression into new curly braces?

So, if I have something like this:

if (a>b) return true; 

and I decided later that I want to change it to this:

 if (a>b) { a++; return true; } 

Is there a faster way to have existing code under an if statement directly in newly made curly braces? Since at present, if I were to add curly braces after creating the if statement in the first example, I would have to cut out β€œreturn true” from the new curly braces and paste it between the newly created curly braces. It looks like this:

 if (a>b) { } return true; 

and it is quite annoying. Is there a fix or should we manually copy and paste the existing line between the brackets?

PS I am using Microsoft Visual Studio 2015 ver 3 and programming in C #, but I think that this problem also occurs in other languages, for example, in C ++.

+5
source share
5 answers

Highlight the code and press Alt + Up Arrow. Move the code down with Alt + Down Arrow. Works with multiple lines. In addition, you do not need to select the entire line. As long as one character is highlighted, it works.

https://blogs.msdn.microsoft.com/zainnab/2013/07/01/visual-studio-2013-preview-moving-lines-of-code/

+6
source

I don't know a faster way, but you can try adding the bottom bracket first and then the top bracket next to if. The only problem is that it will automatically format the bottom bracket that you add if you don't come back and delete and add it after the fact.

Another option, which may not be very bright, is to highlight "return true", right-click for the context menu and select "surround with" and select if (or while or for.) This will create a block and move the cursor so that you can enter a condition. (Hot Key Chord - Ctrl + K, Ctrl + S.)

0
source

Some options:

  • Use R #. Then, when you are going to add a++; , first enter an open shape with the cursor just before the "r" return , and it will add closure for you, and when you then press Enter, you are ready to type a++; . Just 1 or 2 keystrokes, depending on what you want. (This is configurable in R #, so your mileage will depend on this).

  • Subjective, perhaps, but this is one of the good reasons not to write code, such as the original, in the first place, and instead use curly braces for even one block of statements. If this is too unpleasant for you, put the individual instructions on the same line as if()

0
source

Alex has a great answer. In addition, if you do not want to translate the code into if after creating it, you can also highlight the code that you want in the body. Then press ctrl + K, S (or find "Surround with" in the right-click menu), type if and press enter.

This will create an if and paste the highlighted code into the if body.

0
source

MissingBraces allows you to add if / else / for / foreach commands as a quick action.

0
source

All Articles