C # style: May properties be grouped with their support fields?

I like to organize simple properties as follows:

private int foo; public int Foo { get { return foo; } set { // validate value foo = value; } } 

I played with StyleCop and it yells at me for posting the fields after the constructors. Is this style generally accepted as long as the field never refers outside of the property? Note. I understand that there are personal preferences, but I wonder if there is a general opinion regarding this problem.

+4
source share
4 answers

Yes, that seems reasonable to me.

Usually I put all the fields and properties at the top, then the constructors, then the methods, but if you want to put them after the constructors, this also seems reasonable.

+6
source

If your properties are simple data access, use automatic properties:

 public int Foo { get; set; } 

The compiler will create a private member variable behind the scenes on your behalf.

In particular, for your question do not invest too much in tools such as ReSharper or StyleCop. Some of the ways code is formatted and what they complain about are really a matter of preference. I do not put member variables next to their public properties, but I see how convenient it is.

+3
source

May? Since this only affects the people in your team, you need to figure out what they think best and go with it. The Cop style is often a little ... overboard according to his recommendations.

I usually put them after the property, as the above space is reserved for documentation.

 // placed up here, it looks kinda weird, imho // private int foo; /// <summary> /// The index of the Foo in the <see cref="Bar"/> /// </summary> public int Foo { get { return foo; } set { // validate value foo = value; } } private int foo; 
+1
source

This may be a matter of preference, but it seems better than mixing with private members.

I usually use a nested area to support the fields inside the property area, since it does not interfere with the visual comments of the studio, and yet they are grouped into it.

+1
source

All Articles