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?
Rather than grouping by visibility or by type of item (field, property, method, etc.), how about grouping by functionality?
This is an old but still very relevant question, so I'll add this: What's the first thing you look for when you open up a class file that you may or may not have read before? Fields? Properties? I've realized from experience that almost invariably I go hunting for the constructors, because the most basic thing to understand is how this object is constructed.
Therefore, I've started putting constructors first in class files, and the result has been psychologically very positive. The standard recommendation of putting constructors after a bunch of other things feels dissonant.
The upcoming primary constructor feature in C# 6 provides evidence that the natural place for a constructor is at the very top of a class - in fact primary constructors are specified even before the open brace.
It's funny how much of a difference a reordering like this makes. It reminds me of how
using
statements used to be ordered - with the System namespaces first. Visual Studio's "Organize Usings" command used this order. Nowusing
s are just ordered alphabetically, with no special treatment given to System namespaces. The result just feels simpler and cleaner.I don't know about a language or industry standard, but I tend to put things in this order with each section wrapped in a #region:
using Statements
Namespace
Class
Private members
Public properties
Constructors
Public methods
Private methods
I keep it as simple as possible (for me at least)
Enumerations
Declarations
Constructors
Overrides
Methods
Properties
Event Handler
I would recommend using the coding standards from IDesign or the ones listed on Brad Abram's website. Those are the best two that I have found.
Brad would say...
I prefer to put the private fields up at the top along with the constructor(s), then put the public interface bits after that, then the private interface bits.
Also, if your class definition is long enough for the ordering of items to matter much, that's probably a code smell indicating your class is too bulky and complex and you should refactor.