user1617243
user1617243

Reputation: 59

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!

Upvotes: 2

Views: 1946

Answers (4)

Dmitry Osinovskiy
Dmitry Osinovskiy

Reputation: 10118

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.

Upvotes: 1

thersch
thersch

Reputation: 1396

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:

enter image description here

Unfortunatly this does not work for if-else. So you need another pattern like so:

enter image description here

Then you can set pattern's severity in Pattern Catalog dialog and can click Search now.

Upvotes: 1

Matten
Matten

Reputation: 17621

JetBrains Resharper gives you the possibility to do such code refactorings by a short keystroke.

Upvotes: 3

Related Questions