views:

182

answers:

6

I've seen (and used) on various projects this layout, with a group of fields followed by a group of properties:

private int MyIntField;
private string MyStringField;

public int MyInt { 
    get { return MyIntField; }
    set { MyIntField = value; }
}    
public string MyString { 
    get { return MyStringField; }
    set { MyStringField = value; }
}

And I've also encountered this layout with fields next to their property:

private int MyIntField;
public int MyInt { 
    get { return MyIntField; }
    set { MyIntField = value; }
}    

private string MyStringField;
public string MyString { 
    get { return MyStringField; }
    set { MyStringField = value; }
}

Is there a reason to consider one better than the other? I think most coding standards recommend Option #1, but sometimes it's handy having the field next to the property that operates on it.

Note: I'm assuming non-trivial properties that can't use auto-implemented properties.

+7  A: 

I think it is whatever the team feels comfortable with. Settle on a standard for the project/company/language and stick to it. I prefer the private variables all together, the methods/interfaces together, the private members....I think you get the point.

kenny
+3  A: 

I group them at the top of the class.

In fact the only thing that is over my private attribute is all constant of the class.

Daok
+2  A: 

I'd do the latter approach, since it's a convention that helps me to see at a glance whether a private member has a public getter/setter or not. Not a huge deal either way, though.

MusiGenesis
+1  A: 

To reiterate what Kenny said above, it's really all about the coding standards of your organization. It's hard to objectively classify one style over the other, although everyone seems to have their own opinion.

I generally tend to prefer having data and methods groups by access modifier, and so in this case would prefer Option #1. This is to emphasize the interface, not the design. That is, I could transparently change the implementation of the MyInt modifier in the future (maybe I don't really need to store a backing variable).

Scott Wegner
+3  A: 

I kinda like to have the fields grouped at the top and the properties somewhere else. This is also what Microsoft StyleCop recommends.

hangy
+1  A: 

As a side note where do auto properties fit in?

http://stackoverflow.com/questions/9304/c-30-auto-properties-useful-or-not

JaredCacurak