Visual Studio adding space after if-statements

China☆狼群 提交于 2019-12-08 15:29:19

问题


Sometimes (but not always!?) when I paste or end a line with a semi-colon, Visual Studio will add a space after the if statement! For example, when pasting, this

if()

will turn into this:

if (condition)

and, when completing a line, this

if(condition)
    DoSomething()

will turn into this:

if (condition)
    DoSomething();

Having to constantly delete this space (sometimes twice!) is driving me absolutely Bonkers! It seems to happen with if and while but not for.

I cannot find anything relating to this in the VS options. I do have Resharper installed, but it is set to not add the space automatically:

Why is Visual Studio punishing me?


回答1:


In the Visual Studio options, under Text Editor / C# / Formatting / Spacing, in the "Set other spacing options" part, there's an option for "Insert space after keywords in control flow statements".

I suspect you'll find you've got that checked, and you don't want it to be. (I have it checked deliberately :)




回答2:


Disable auto-formatting as you see fit.

Tools->Options->Text Editor->C#->Formatting->General.

All are checked by default in my C# Express 2010 config:

  • Automatically format completed statement on ;
  • Automatically format completed block on }
  • Automatically format on paste



回答3:


Another good trick is leaving the coding as is and hit CTRL+K+D it will auto-format your code and fix the spaces




回答4:


Visual Studio behavior seems to be a little inconsistent here. I tested everything here with the "Automatically Format" settings all checked in the Options, as shown in the following image:

I used the following code:

if(true)
{
   int m = 3;
}

If I copy/paste the code above into Visual Studio, Visual Studio will automatically apply formatting - resulting in a space after if.

If I type the code in manually, Visual Studio will not automatically add a space after if, even after I complete the if line with a closing parenthesis, and even after I complete the if block with a closing bracket.

As mentioned in another answer, if I CTRL+K+D to format the entire document, Visual Studio does insert a space after if.

This is slightly frustrating because if I'm manually writing code I get no space after if (out of habit) but if I paste code or format my document I do get spaces.



来源:https://stackoverflow.com/questions/4208231/visual-studio-adding-space-after-if-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!