craig157
craig157

Reputation: 385

How to Remove Braces on Single-Line Statement?

Could anyone advise how to remove braces from any single-line statements? (Excluding the obvious just delete the braces manually)

Using C# in Visual Studio.

So instead of:

if (thingy is null)
{
    throw new ArgumentNullException(nameof(thingy));
}

Have the alternative:

if (thingy is null)
    throw new ArgumentNullException(nameof(thingy));

I have tried running CodeMaid and also changing the CodeCleanup (which just changes it back to having braces). I am happy to try any recommended Extensions etc to get this sorted.

Upvotes: 6

Views: 3051

Answers (4)

johnml1135
johnml1135

Reputation: 4957

Regex to the rescue! Do a find/replace one at a time (checking for the pesky case below if you are suspicious of it) in VSCode with regular expressions enabled and put in:

  • Find: (if \(.*\)\n|else\n)\s*\{\n([^{};]+;\n)\s*\}\n+
  • Replace: $1$2

Note that this Assumes well formatted code by Csharpier, etc. It will also work with else clauses as well. Also, watch out for:

if ~~~
{
  if ~~~
    ~~~
}
else 
  ~~~

If you remove these braces, the else will attach to the second if! You have been warned!

Also, adding braces back can be done with https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0011.

Upvotes: 0

StingyJack
StingyJack

Reputation: 19479

You should not get into omitting braces on single line conditional as a habit. It is easy for someone (you or another person) to make a little mistake with it that creates a bug you have to deal with later.

Now I will get off my soapbox and share an even shorter null guard:

public void MyFunction(object thingy)
{
   _ = thingy ?? throw new ArgumentNullException(nameof(thingy));
   etc...

Nice and terse, and no risk of missing brace issues. For strings I will use an extension method to get the same one liner.

  public static string NullIfWhiteSpace(this string s)
  {
      return string.IsNullOrWhiteSpace(s) ? null : s;
  }

Then I can do:

public void MyFunction(string stringy)
{
   _ = stringy.NullIfWhiteSpace() ?? throw new ArgumentNullException(nameof(stringy));
   etc...

I do something similar for empty lists and dictionaries.

Upvotes: -6

Richard
Richard

Reputation: 109090

This is not a standard refactoring in Visual Studio. But there are extensions that add this.

Eg. Roslynator has its Remove Braces refactoring.

Upvotes: 5

Chandraprakash
Chandraprakash

Reputation: 947

If you are using Visual Studio 2019 Preview, then you can achieve your need in 2 simple steps.

enter image description here enter image description here

Upvotes: 6

Related Questions