ReSharper - force curly braces around single line

 ̄綄美尐妖づ 提交于 2019-11-29 22:44:42

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

Ryan is correct (note however that the his link refers to R# 2.0 help). The specific procedure is as follows:

  1. Go to ReSharper > Options > Languages > C# > Formatting Style > Braces Layout
  2. Set "Braces in "if-else" statement" to "Use braces for multiline"
  3. After saving the changes, select a scope to reformat (could be a code selection, file, folder, project, solution - anything you want).
  4. Choose ReSharper > Tools > Cleanup Code.
  5. 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"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!