Clyde
Clyde

Reputation: 8145

Visual Studio/C# auto-format. Can I control newline after attributes

Visual studio keeps doing this:

[DataContract] 
public class MyContract 
{
    [DataMember]
    public bool MyBool { get; set; }
    [DataMember]
    public string MyString { get; set; } 
}

I would like this:

[DataContract] 
public class MyContract 
{
    [DataMember] public bool MyBool { get; set; }
    [DataMember] public string MyString { get; set; } 
}

No big deal if the 'public class MyContract' is on the same line as the [DataContract].

Visual studio seems to have a lot of detailed autoformatting options, but I can't find any regarding newlines after attributes. Am I missing something here? Or is it just not available.

EDIT: At very least, I'd like a "don't change what I entered" formatting option, as opposed to a "always insert" or "always remove" newline option. It's super-annoying that it keeps unformatting my code after I type.

Upvotes: 24

Views: 10496

Answers (6)

Alexey Slusar
Alexey Slusar

Reputation: 1

It is ReSharper. Extensions/ReSharper/Options/Code Editiong/C#/Formatting Style/ Line Breakes and Wrapping:

Line Breaks and Wrapping: Line Breaks and Wrapping

Upvotes: -2

mkatic
mkatic

Reputation: 151

What worked best for me was to disable auto format on ; and paste. I hardly ever want auto format at these times anyways. This allows you to type out attributes and move them around without pesky interference.

Options > Text Editor > C# > Formatting > General

Settings screenshot

Upvotes: 0

Mike
Mike

Reputation: 471

ReSharper can do that. It has options for:

  • Place type attribute on same line
  • Place method attribute on same line
  • Place property/indexer/event attribute on same line (this is the one you want)
  • Place field attribute on same line

It costs a few bucks but if you're as obsessive as I am it's worth every penny. ;)

I also remap Ctrl+K, Ctrl+D to ReSharper's silent format code to experience formatting bliss.

Upvotes: 2

Jay Zeng
Jay Zeng

Reputation: 1421

Yeah, Ctrl+E, D is your friend. You can optimize the formatting in Text editor options

Upvotes: -4

Agent_9191
Agent_9191

Reputation: 7253

Not sure if it works for attributes, but look under Tools -> Options -> Text Editor -> C# -> Formatting -> Wrapping -> Leave block on single line or Leave statements and member declarations on the same line.

Upvotes: 2

Abel
Abel

Reputation: 57159

What I usually do is hit Ctrl-Z the very moment autoformat jumps in where I don't appreciate it.

I.e., on a closing accolade, which formats a whole class or method. Type the closing accolade, see it changing the way you don't like it and then hit Ctrl-Z. (I know you were looking for an actual option, I don't know if any exists).

Upvotes: 7

Related Questions