Is there an official C# guideline for the order of items in terms of class structure?
Does it go:
- Public Fields
- Private Fields
- Properties
- Constructors
- Methods
?
I'm curious if there is a hard and fast rule about the order of items? I'm kind of all over the place. I want to stick with a particular standard so I can do it everywhere.
The real problem is my more complex properties end up looking a lot like methods and they feel out of place at the top before the constructor.
Any tips/suggestions?
There certainly is nothing in the language that enforces it in any way. I tend to group things by visibility (public, then protected, then private) and use #regions to group related things functionally, regardless of whether it is a property, method, or whatever. Construction methods (whether actual ctors or static factory functions) are usually right at the top since they are the first thing clients need to know about.
the only coding guidelines I've seen suggested for this is to put fields at the top of the class definition.
i tend to put constructors next.
my general comment would be that you should stick to one class per file and if the class is big enough that the organization of properties versus methods is a big concern, how big is the class and should you be refactoring it anyway? does it represent multiple concerns?
As mentioned before there is nothing in the C# language that dictates the layout, I personally use regions, and I do something like this for an average class.
It makes sense to me anyway
From StyleCop
private fields, public fields, constructors, properties, public methods, private methods
As StyleCop is part of the MS build process you could view that as a de facto standard
My preference is to order by kind and then be decreasing visibility as follows
I know this violates Style Cop and if someone can give me a good reason why I should place the implementation details of a type before its interface I am willing to change. At present, I have a strong preference for putting private members last.
Note: I don't use public or protected fields.
I know this is old but my order is as follows:
in order of public, protected, private, internal, abstract
I also like to write out properties like this (instead of the shorthand approach)