ReSharper - force curly braces around single line - c#

Can I configure ReSharper to fix C# code when curly braces are not used to surround a single-line code block, like this:
if (blnSomeCondition)
DoSomething(); // complain
if (blnSomeOtherCondition)
{
DoSomethingElse(); // don't complain
}
Thanks

In the new version of ReSharper (2016.x) is has been moved to the Code Style.
UPD1: for ReSharper 2017.x
UPD2: for ReSharper 2018.x
UPD3: for ReSharper 2019.x
UPD4: for ReSharper 2020.x

Ryan is correct (note however that the his link refers to R# 2.0 help). The specific procedure is as follows:
Go to ReSharper > Options > Languages > C# > Formatting Style > Braces Layout
Set "Braces in "if-else" statement" to "Use braces for multiline"
After saving the changes, select a scope to reformat (could be a code selection, file, folder, project, solution - anything you want).
Choose ReSharper > Tools > Cleanup Code.
Profit.
Remember that Code Cleanup does numerous things and they're not only related to code formatting (see details at http://www.jetbrains.com/resharper/webhelp/Code_Cleanup__Index.html), so use the feature wisely.

Gorohoroh's solution is close, but instead of selecting "Use braces for multiline" I had to select "Add braces" to force it to add the braces in the single-line scenario. And I had to set that in all six dropdowns under "Force Braces" to catch all the scenarios:
What I was really hoping for was to be able to set up ReSharper to do a yellow warning or red error when the rule was violated, but I haven't found a way to do that. Because you're right, Gorohoroh, Cleanup Code does a lot of stuff and I'd like to have the option to look at and fix the rule violations one at a time.
Thanks for your help!

For ReSharper 2016.2.2.
You should edit your profile for cleaning up. The proper item is called Add/Remove braces for single statements in "if-else", "for", "foreach", "while", "do-while", "using". This item can be found within the C# => Code styles item.
If the item is checked, braces will be added; if unchecked, braces will be removed.
Note: adding doesn't work now (don't know why - perhaps, too fresh version of ReSharper). However, if you will uncheck the mentioned item, the existent braces around single statements will not be removed.
UPD: The problem solved, see the first two comments under this post.

You can configure it as seen on the screenshot.
PS: for the ones to have problem seeing Imgur.com urls -> https://ibb.co/b4xijT

Just if it can help somebody else to save time, on one machine of my company, following Sergey advices was not enough despite the great quality of his post.
On concerned setup (VS2017, R# 2019, both up to date) these settings on R# side were already good, but I also had to modify it in Visual Studio options :
In Options window, go to Text editor -> C# -> Code style ->
Formatting -> General,
Check "Perform Additional code cleanup
during formatting" and "Add/remove braces for single-line control
statement"

Well it is moved again. The new place is under the Syntax Style on version ReSharper 2020.01.
Go to ReSharper > Options > Code Editing > C# > Syntax Style > Braces
Here is the screen shot from ReSharper 2020.01

Related

how do i turn off auto-insert of newline after code block?

I might have some degree of OCD, maybe that's why it bothers me when I close a line with ';' below a while{} for{} or other code block and resharper would automatically insert a line break above my line.
I DO NOT want an extra line.
I looked through the Editing option page under braces and new lines, but nothing seems to jump out.
sample:
if (true){
GC.Collect();
}
string s = "Any statement here, ending the line with ';' causes newline above";
Visual Studio (2019) has these formatting settings. I'm assuming you're using VS and resharper isn't doing the formatting.
Tools > Options > Text Editor > C# > Code Style > Formatting > New Line
Find "Place open brace on new line for control blocks". There are a bunch others there as well.
In ReSharper options: Code Editing->C#->Formating Style->Blank Lines - set After statements with child blocks to 0.

resharper code formatting introduces needless linebreak on starting parens

When I have simple wrap enabled on Wrap invocation arguments, I often end up with a formatted line like:
string.Format(
"example string tralala {0} {1}",
foo, bar);
no combination of settings I find prevents this line break other than enabling chop if long. unfortunately that can be a bit of a line hog (it forcibly makes each argument take a line if a function call takes up more than your max word-wrap space).
Is there any solution to this that I am overlooking?
In Resharper 9
Go to Resharper(from Visual Studio Menu)->Options->Code Editing->C#->Formatting Style->Line Breaks and Wrapping
and Uncheck Wrap Long Line from Line Wrapping option
There are a few settings you can use to format your code just the way you like it in re-sharper. in Visual Studio Go: Tools>Options>Re-sharper and click the Options button there again.
Then under the Code Editing section, under c#>Formatting Style. You can use one of the following settings:
Prefer wrap before ( in declaration\invocation
Prefer warp after ( in declaration\invocation
Or set the wrap invocation argument to either (this is most likely the one need setting)
chop always.
chop if too long.
simple wrap.
The un-tick the wrap long lines all together right on top op the *line wrappingsection, willstop-wrapping`, but you'll need to go through these setting to get it just right - or to get it to format the way you code.

How to automatically insert optional curly braces in C#?

In C# (as in Java), curly braces are optional for e.g. if blocks and loops that only contain a single statement:
if (condition) DoSomething();
I am looking for a tool that inserts missing optional curly braces for my entire solution, turning the above code into something like this:
if (condition) {
DoSomething();
}
I know that Eclipse can do this for Java. Unfortunately, I am not aware of a tool that can do this for C#. I would be grateful for suggestions! Thanks!
JetBrains Resharper gives you the possibility to do such code refactorings by a short keystroke.
You could write a ReSharper Replace Pattern.
Add a pattern to Pattern Catalog by (in ReSharper 5.1.3 ReSharper->Tools->Pattern Catalog->Add Pattern).
Then you write your pattern like so:
Unfortunatly this does not work for if-else. So you need another pattern like so:
Then you can set pattern's severity in Pattern Catalog dialog and can click Search now.
With ReSharper, go to ReSharper | Options -> Code Editing | C# | Formatting Style | Braces Layout and change neccessary options in Force Braces section to Add braces. Then find your solution in Solution Explorer, invoke context menu and choose Cleanup code... from it. Select Default: Reformat code and press Run. But be carefull! It would also reformat all code files in your solution. Be sure to backup if you do it the first time, just in case you wouldn't like ReSharper's default formatting. Maybe you would need to play with formatter settings to make it suit you.
you can use Brace Completer
http://visualstudiogallery.msdn.microsoft.com/0e33cb22-d4ac-4f5a-902f-aff5177cc94d

How to find the suspicious statement, like "Name = Name;" in C# by Regex?

My C# code has a lot of statement like "this.Name=...". In order to make my code neat, I let the text editor to replace all "this." to nothing. The code still worked. But later I fund it caused me a lot of new troubles for I wrote some statements like:
this.Name = Name; // the second Name is a parameter.
After the replacement, it became:
Name = Name;
Now, I met too much code. How to find the suspicious code like "Name = Name;" by Regex in VS 2010?
Thanks,
Ying
Why would you want to use Regex when you can simply compile the solution and look for the CS1717 warning:
Assignment made to same variable; did
you mean to assign something else?
Also note that in C# it is a good convention to have your parameters start with lowercase letter.
I would agree that Darin's approach is more robust and should be done first. However you might
have commented out sections of code which will be missed with this approach.
To try and find those you can use "Find in Files". In the Find box tick "Use regular expresssions" and enter {:i}:Wh*=:Wh*\1
:i C Style identifier ("tagged" expression by enclosing in braces)
:Wh* Zero or more white space chars
\1 back reference to tagged identifier found
This approach might bring back some false positives so you could try :Wh+{:i}:Wh*=:Wh*\1:Wh+ if there are too many but at the risk of missing some matches (e.g. where the closing comment mark is immediately after the assignment statement)
You could restore your last commit from your CVS, if you haven't changed too much since.
The problem with doing what you ask is that there might be other cases where "this" shouldn't have been replaced and you haven't seen the problem yet.

Any way to surround code block with Curly Braces {} in VS2008?

I always find myself needing to enclose a block of code in curly braces { }, but unfortunately that isn't included in the C# surround code snippets, which seems to be an oversight. I couldn't find anything on building your own surround snippets either (just other kinds of snippets).
I am actually running Resharper too, but it doesn't seem to have this functionality either (or I haven't figured how to activate it).
We have a coding standard of including even a single line of code after an if or else in curly braces, so if I could just make Resharper do that refactoring automatically that would be even better!
Here is a quick and dirty snippet to do just that.
To Install:
Save the code as SurroundWithBraces.snippet into "<my documents>\Visual Studio Version\Code Snippets\Visual C#\My Code Snippets"
To use:
Select block of text.
Press Ctrl+K, Ctrl+S
Chose My Code Snippets, braces
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>braces</Title>
<Shortcut>braces</Shortcut>
<Description>Code snippet to surround a block of code with braces</Description>
<Author>Igor Zevaka</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="csharp">
<![CDATA[{
$selected$ $end$
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
In ReSharper 4.5, curly braces are included as one of the built-in 'Surround Templates':
Select the text that you want curly
braces around.
ReSharper -> Code -> Surround
With... -> {}
or
ALT + R -> C -> S -> 7
or
Ctrl+E, U -> 7 (Visual Studio scheme)
or
Ctrl+Alt+J -> 7 (ReSharper 2.x/IDEA scheme)
How about:
Ctrl-X, {, Ctrl-V, }
You could even bind that to a macro.
In VS2015 there is an experimental feature that supports it by selecting the text and typing in }.
See here how to enable.
Make your own custom code snippet for doing that.
You can use snippy to create your own http://blogs.msdn.com/gusperez/articles/93681.aspx
or just use an XML editor to create one.
Put the file in My Documents\Visual Studio XXXX\Code Snippets\C#\My Code Snippets
To complete Ray Vega's answer, for those using Resharper, I figured out you can associate a shortcut to Resharper commands.
Just do the following (I am using VS 2010):
go to Tools->Options
In the listbox, extend Environment and click on Keyboard.
In the field under "Show commands containing:" enter "resharper.resharper_surroundwith"
In the field under "Press shortcut keys" enter your shortcut (eg: I choose Ctrl+R,Ctrl+S) and click Assign and then Ok.
That's it. you can select your code, and type that shorcut to view all Resharper SurroundWith commands. Just enter 7 to put braces.
Edit: This turns out to be part of DxCore, from DevExpress. Leaving here so others notice, but basically I was wrong wrong wrong. To make this particular menu go away you disable it in the 'add ins' dialog; unloading devexpress from their own menu just unloads CodeRush/Refactor, not the base support libraries.
The is (not!) a built in way to do it. I don't know if you can bind a key to it or not. Also, this embed doesn't do anything if you only select one line, so it probably won't work right if your stuff is on one line after the "if".
Select the block
Right Click
Choose "Embed Selection"
Choose "Block {}"
Note: I have DexExpress installed, but this menu is there even when it isn't loaded, and I could swear it is there even when it isn't installed. However, if I am mistaken...
This honestly seems like something that would be best to ask r# for, a user contrib perhaps?
For new comers in 2022,
Until this extension is available in the market, you have to clone the repo, build it and install it.
source
You can wrap a code block with braces by
Highlight the code block
Ctrl e -> Ctrl u
select option 7
I know this is an old question but I hope it helps someone
Ref: Wrapping multiple statements in braces

Categories

Resources