简体   繁体   中英

Format document in Visual Studio to insert braces?

Is there a way to "Format document" in Visual Studio to insert braces around single-statement blocks for C# code? For example this:

if (x)
    y();

... would become something like:

if (x) { y(); }

The auto formatting seems to deal with indentation but not this brace insertion. Is there a way to do it?

In case you have resharper you can configure it to force braces depending on your criteria. Than in the existing code press ctrl alt shift f , it will format whole file. Or select just part of the code, in this case resharper will format just selection

PS ctrl alt f opens clean up dialog. You can configure cleanup options.

在此处输入图片说明

Actually, there seems to be something built-in to Visual Studio to do this.

If you go to Tools -> Options -> Text Editor -> C# -> Formatting -> New Lines and make sure that you have Place open braces on new lines for control block checked.

Then, go to your document and use the key combination CTRL K D , this should reformat your document and add the curly braces.

I gave a vote to Gimly's answer as it is pretty much correct. These things change over time of course. I would have added a comment but I wanted to paste in some images. Location of settings in VS2019 is at: 在此处输入图像描述

Uncheck the appropriate check boxes and select OK.

The shortcut key did not work, which is a shame because, I love them! This documentation suggests that you use CTRL-K, CTRL-E or, you use the broom icon:

在此处输入图像描述 .

Neither option worked for me perhaps because, that is not the intention, given the list of options. However, if you mark and cut all your code and then, paste the code back into the file, the new standard is adopted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM