Reputation: 60
First of all, I don't want to start a coding styles war, so please only reply if you are answering the question.
I've encountered a couple of people who put their fields at the top of the class. Could anyone who does this explain the rationale behind it?
Many thanks
Upvotes: 2
Views: 450
Reputation: 22443
If I'm not using Auto Properties I like to keep the backing store next to the property. I like private state fields, static values, and constants, next constructors, then properties, followed by instance methods and then static methods. If I have nested classes those either go to the top of the class if they are used by the entire class or right before the group of methods they are used with.
public class MyClass
{
public class MyNestedClass
{
}
// constants
// private state fields
// private static fields
// constructors
// properties
// static properties
// methods
// static methods
// finalizer if required
}
Upvotes: 2
Reputation: 180948
I put mine at the top of the class, because it causes the properties to cluster together, without the fields in between breaking them up.
But it's largely a matter of preference. Intellisense insures that you always know what an identifier does, and "Go to definition" insures that it doesn't really matter where you put the fields.
Upvotes: 1
Reputation: 77616
One rationale (at least before auto-properties came into existance) was to group all the state information at the top of the class because it goes a long way towards summarizing what the methods that follow will accomplish.
Upvotes: 1
Reputation: 4948
I like to group fields at the top of a class only for code organizational purposes. I find it easier to find what I'm looking for more quickly than if fields were spread out amongst the class.
I also typically group other members up by type and also have an internal sort by access modifier.
public class MyClass
{
// Fields
// Constructors
// Properties
// Methods
}
Upvotes: 8