Order of items in classes: Fields, Properties, Constructors, Methods
Asked Answered
K

16

813

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?

Kauffmann answered 29/9, 2008 at 20:23 Comment(5)
Actually, to answer the actual question, no, there is no official guideline. StyleCop implements the guidelines developed for use within one particular group in Microsoft. This is not an official guideline, and may not even be uniform among groups in Microsoft.Hydrostatics
One easy trick is to see the metadata of some complex class in .net (F12 in VS). You will come to know how its ordered at least for the public and protected members.Robot
This question isn't opinion-based, as it asks whether there's an official guideline. Either there is a guideline or there isn't!Imagination
@Robot I realize this is an old comment, I like the trick you mentioned, but it's worth mentioning that it won't show private or internal members (I believe). Nice way of seeing public and protected, however. We can see the source of .NET Framework classes, here referencesource.microsoft.com tooNightingale
@SimonMᶜKenzie There are multiple questions here, "Any tips/suggestions?" definitely calls for opinions.Ankle
S
1270

According to the StyleCop Rules Documentation the ordering is as follows.

Within a class, struct or interface: (SA1201 and SA1203)

  • Constant Fields
  • Fields
  • Constructors
  • Finalizers (Destructors)
  • Delegates
  • Events
  • Enums
  • Interfaces (interface implementations)
  • Properties
  • Indexers
  • Methods
  • Structs
  • Classes

Within each of these groups order by access: (SA1202)

  • public
  • internal
  • protected internal
  • protected
  • private

Within each of the access groups, order by static, then non-static: (SA1204)

  • static
  • non-static

Within each of the static/non-static groups of fields, order by readonly, then non-readonly : (SA1214 and SA1215)

  • readonly
  • non-readonly

An unrolled list is 130 lines long, so I won't unroll it here. The methods part unrolled is:

  • public static methods
  • public methods
  • internal static methods
  • internal methods
  • protected internal static methods
  • protected internal methods
  • protected static methods
  • protected methods
  • private static methods
  • private methods

The documentation notes that if the prescribed order isn't suitable - say, multiple interfaces are being implemented, and the interface methods and properties should be grouped together - then use a partial class to group the related methods and properties together.

Snowbound answered 22/11, 2008 at 6:41 Comment(25)
I would like to thank you for taking the effort in this post. I'm attempting to make StyleCop stuff a standard (even if just to be consistent and make it easy to find things) and this is valuable.Saratov
Personally, I find the ordering of static methods annoying. I can see the argument for static public methods coming first, but I normally want private static methods after members. They're utilities after all.Snowbound
Thanks, this helped me quite a bit with my latest changes to my StyleCop assistance Add-in (sweeper.codeplex.com). The only thing extra I'd point out is that many of the element types do not support static.Subalpine
I liked the partial class tipMinier
Just a note on partial classes. Given that during compile time all partials are compiled into a single type, I would always try to ensure a good reason for creating that additional overhead. The main reason for partial classes are to extend auto-generate source code or when working on large projects to allow multiple developers to work on the same class but separate files.Imbed
@FrançoisWahl Is the overhead associated with the compiler combining partial classes into a single type that large?Theresiatheresina
@dav_i: If the overhead is noticable or not I don't realy know, I have not run any performance tests on that. It most likely is not noticable but as a general rule of thumb I try to only create partials when extending auto-generated code. Here is also a good resource on partials: 4guysfromrolla.com/articles/071509-1.aspxImbed
@FrançoisWahl I imagine the overhead isn't too bad and that the benefits of readability will save you more time in the long run :) Interesting article - I didn't realised partial methods existed!Theresiatheresina
Another point. What is the standard('s) way of grouping within public static fields, etc - i.e. does one go by field name or by type then field name? (e.g. public int a; public bool b; or public bool b; public int a;?Theresiatheresina
One of the only thing I avoid is splitting fields and their associated accessor properties. I see this kind of pairs as being one field.Transpolar
What does “Interfaces“ (between Enums and Properties) mean? Explicit interface implementations or...?Spoilsport
@FrançoisWahl - I use partial classes a lot in my large projects. I have noticed absolutely no compiling overhead, and the largest project is around 600k lines. I dislike having a class with dozens of accessors and methods. On large classes I will split it into separate .cs files, one for each method. I find this also makes it much simpler to look at the Solution Explorer and instantly visually see all of the available methods in a class, instead of having to open the file and scan through it.Vandyke
FYI your link to the style cop rules is broken.Mcadams
StyleCop ordering rules can be found at github.com/Visual-Stylecop/Visual-StyleCop/wiki/Ordering-Rules.Ebullition
With the 'new' C# automatic properties I don't really like the fields -> constructors -> properties order, I feel like the properties should come after the fields if there's only like 1 or 2 of them. Hard to keep "one or two" as a definite rule though so I keep following this...Overplay
Does anyone know if this is available as a Resharper layout file?Growing
I would group togheter all the static stuff aside from the instance stuff. It's very likely that you work on multiple items, static members and static fields so it makes great sense to have them close. On the other hand, when you're looking for a static member you know very well that is static so looking in another place shouldn't be a great concern. I found no benefit in interleaving static members with dynamic ones; that is the third ordering criteria should be the first in my opinion.Oshaughnessy
Style Cop is using an ordering that made sense in the old C days but no more. In OO clients of your class should use the public interface of your class (and if you must it's public properties). Place those at the top to facilitate the users of your class. If you use a DI container, your constructor(s) are not very relevant to your readers as well, the can go with all the other stuff, which you only need when working on the inner workings of the classIotacism
While this answers the first half of the question excellently, I wanted to add a note toward the second part: if your properties are complex and look method-like, then the property should call a method. I see the same thing all the time regarding events. Do the actual work down in private methods and classes. If the code is broken down small enough the StyleCop ordering gets to making more sense.Somniloquy
What about auto-implemented properties? Should they stick with fields or other properties?Knife
These StyleCop rules makes no sense to me. Why are delegates and events clubbed together? One is a type, other is a member. Events belong near properties (or other members like methods, fields). Why are types like enums, delegates in the middle but classes and structs at the end? Why is internal above protected internal when former is the more restrictive scope? There is no logical order for this whatsoever. I raised this in one of the relevant github issues and the answer I got was: "meh, it was how some guy decided to do back in the day".Robot
I've followed these StyleCop ordering guidelines for many years, but never really questioned the reason, especially as modern IDEs make it easy to find members within a class. I've (only just) read the excellent "Clean Code" by Robert (Uncle Bob) Martin, which advocates that when one method calls other methods, you try to place the callees right after the caller which means methods with different visibilities being mixed together, but I do like the idea of this for readability and less jumping around inside a class when following the flow of logic.Heartsease
Where does the virtual & override methods fall in the styelcop? Any suggestions!!!Vines
Why would fields and properties be put in different places? eg fields before the constructor and properties after.Syncarpous
Modern IDE-s and code editors normally parse the file and show an outline of the properties and methods, likely alphabetical or by category or something. This fact greatly makes the actually order in the source file moot. Worse moving around code just for the sake of "standard" will make versioning with some diff function harder not easier.Tachycardia
I
49

Rather than grouping by visibility or by type of item (field, property, method, etc.), how about grouping by functionality?

Iow answered 29/9, 2008 at 20:30 Comment(6)
If "sorting" using the StyleCop recommendations it is a kind of functionality. There is a good reason why some methods are public and others are private. The code is really better readable: If opening a class's .cs file I immediately see the public methods which are "more important" than the private ones (for the guy which is using that class)Freehanded
If you've got so many methods, properties, etc. in your class that you need to group them by section, maybe that's a sign that the class is doing too much?Iow
Even if the class is small, wouldn't it make sense to group public methods with their corresponding private methods which are only called by this public method?Arielle
+1 if the public method Foo() calls a protected/private InternalFoo() , then that second method better be right beneath DoFoo() in the source, not somewhere further down among other protected/private methods.Slow
grouping by functionality is called a classWingback
+1. If by different functionality you mean "business functionality", then I would disagree. However, if it is "utility functionality", then maybe it makes sense. Say for instance your class has a single business meaning, but is IEnumerable, IDisposable and INotifyPropertyChanged, each interface's implementation requiring slightly more than a single method, then maybe it would make sense to group them together even though the entire class contributes to the same business functionality.Facilitate
B
33

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. Now usings are just ordered alphabetically, with no special treatment given to System namespaces. The result just feels simpler and cleaner.

Burly answered 17/1, 2015 at 9:0 Comment(5)
Class initialization/construction is, in my opinion, convoluted. Fields are initialized before explicit constructors are run, so going further along your argument of essentially putting members in the order they are used/created, initialized fields would be before explicitly declared constructors. Initialized static fields and static constructors make it even more interesting.Defloration
Actually, the order they tend to be looked for by humans, the notion of literary programming that code should first be readable by humans.Burly
Note that primary constructors were removed from the plans for C# 6: https://mcmap.net/q/55143/-primary-constructors-no-longer-compile-in-vs2015Winnick
9 times out of 10, I'm looking for the public interface, which is why I put all of the public members first, followed by internal, followed by protected, and finally by private members.Spongin
maybe for classes with code, and just maybe, but for the classes that contains only data first thing i want to see are properties/fieldsMinuend
S
29

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

Skillful answered 29/9, 2008 at 20:30 Comment(4)
This is exactly how I do it as well. Except between Class and Private Members, I have any Public Constants and Enums etc.Vandyke
Yes, I prefer to keep public properties after private methods. Other people prefer to put the constructor before public properties... but in my head I prefer to have values/constructors/behaviors, in that order. Then "values" is divided as constants/privateMembers/properties and so. Usually I don't use regions, except for some big view-models... well, WPF viewmodels are kind of special, and, in this case I usually put the backing private fields just before each public property. In this case, the set of private field plus the public member is the same unitBuchalter
If your class is big enough that it needs regions to help find things, it's a pretty strong indicator that your class is too big.Surveyor
No one should use regions in production code. If you need regions in your code, then your class is too big - the code should be extracted and put into other classes.Impetus
C
15

I would recommend using the coding standards from IDesign (webarchive) or the ones listed on Brad Abram's website. Those are the best two that I have found.

Brad would say...

Classes member should be alphabetized, and grouped into sections (Fields, Constructors, Properties, Events, Methods, Private interface implementations, Nested types)

Coronary answered 29/9, 2008 at 20:30 Comment(2)
That link appears to just lead to the IDesign home page these days. It appears the coding standards are hidden behind a emailed download link these days #justsayingUltramontanism
Guidelines should have rationale. The rationale for that is: 1. so that you understand, 2. so that you can apply judgment on borderline, subtle, ambiguous, unforeseen or conflicting cases, 3. so that you can adjust when conditions change and some guideline no longer applies.Concupiscent
J
12

My preference is to order by kind and then be decreasing visibility as follows

public methods
public events
public properties

protected methods
protected events
protected properties

private methods
private events
private properties
private fields

public delegates
public interfaces
public classes
public structs
public records

protected delegates
protected interfaces
protected classes
protected structs    
protected records

private delegates
private interfaces
private classes
private structs
private records

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.

Jocelynjocelyne answered 18/12, 2016 at 14:0 Comment(3)
Agreed. I really wonder if the notion of putting the private members first is not a holdover from the C days where variables had to be declared first. I almost always want to see the public interface first, not the class internals.Spongin
That actually makes a lot of sense. I bet it is a holdover from C.Jocelynjocelyne
Some of the biggest gotcha's can be the properties IMO. When there is logic on a getter/setter that you were unaware of, that's going to be much more likely to bite then side effects in methods (which you naturally expect them to be in) Therefore, I prefer properties alongside their fields at the top, so when I'm looking at a class for the first time, I see the gotcha's up top. Where as when I read a method, I normally navigate / jump immediately to the method anywayStoller
H
7

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.

public class myClass
{
#region Private Members

#endregion
#region Public Properties

#endregion

#region Constructors

#endregion
#region Public Methods

#endregion
}

It makes sense to me anyway

Homework answered 29/9, 2008 at 20:31 Comment(5)
Here is to say (just for information) that stylecop does recommend not using regions (SA1124 DoNotUseRegions)Nazi
Microsoft itself is using regions.Tenterhook
@Tenterhook Sure, in a file with 5538 lines, regions are necessary, but that doesn't mean you should use regions in normal files.Fulcher
@Gerwald: I think StyleCop is only for people using StyleCop. It is one out of many standardsBuchalter
@zameb: I would say, the StyleCop rules are one of the most common coding guidelines for C#. When coding in any languages, I am always trying to find the most common set of coding guidelines, and follow them.Nazi
H
7

Usually I try to follow the next pattern:

  • static members (have usually an other context, must be thread-safe, etc.)
  • instance members

Each part (static and instance) consists of the following member types:

  • operators (are always static)
  • fields (initialized before constructors)
  • constructors
  • destructor (is a tradition to follow the constructors)
  • properties
  • methods
  • events

Then the members are sorted by visibility (from less to more visible):

  • private
  • internal
  • internal protected
  • protected
  • public

The order is not a dogma: simple classes are easier to read, however, more complex classes need context-specific grouping.

Hughs answered 29/9, 2008 at 20:40 Comment(0)
J
5

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

Johannejohannes answered 29/9, 2008 at 20:30 Comment(5)
Interesting. Do you use StyleCop regularly?Kauffmann
For one project yes, because it does get used for some MS contract work now and again. It's very annoying grinJohannejohannes
Using StyleCop for a long time and if using that recommendations makes the code really better readable: If opening a class's .cs file I immediately see the public methods which are "more important" than the private ones. The publics are the "interfaces" of the class what it offers and what can be tested (prefer TDD, and Test-First)Freehanded
According to StyleCop public fields should go before private fields stylecop.com/docs/SA1202.htmlLyons
What do you mean by "StyleCop is part of the MS build process"? Is microsoft using StyleCop for all its code?Boresome
A
3

The closest you're likely to find is "Design Guidelines, Managed code and the .NET Framework" (http://blogs.msdn.com/brada/articles/361363.aspx) by Brad Abrams

Many standards are outlined here. The relevant section is 2.8 I think.

Afra answered 29/9, 2008 at 20:29 Comment(0)
O
3

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.

Orlosky answered 29/9, 2008 at 20:36 Comment(0)
K
3

I keep it as simple as possible (for me at least)

Enumerations
Declarations
Constructors
Overrides
Methods
Properties
Event Handler

Keratitis answered 29/9, 2008 at 20:42 Comment(0)
S
3

I know this is old but my order is as follows:

in order of public, protected, private, internal, abstract

  • Constants
  • Static Variables
  • Fields
  • Events
  • Constructor(s)
  • Methods
  • Properties
  • Delegates

I also like to write out properties like this (instead of the shorthand approach)

// Some where in the fields section
private int someVariable;

// I also refrain from
// declaring variables outside of the constructor

// and some where in the properties section I do
public int SomeVariable
{
    get { return someVariable; }
    set { someVariable = value; }
}
Shute answered 7/12, 2017 at 7:8 Comment(0)
F
2

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?

Fiver answered 29/9, 2008 at 20:29 Comment(1)
and once you need regions... you have lost.Fiver
S
2

I have restructured the accepted answer, as to what I think is a better layout:

Within a class, struct or interface:

  • Constant Fields
  • Readonly Fields
  • Fields
  • Events
  • Properties
  • Indexers
  • Constructors
  • Finalizers (Destructors)
  • Interfaces (interface implementations)
  • Methods
  • Classes
  • Structs
  • Enums
  • Delegates

Within each of these groups order by access:

  • public
  • internal
  • protected internal
  • protected
  • private

Within each of the access groups, order by static, then non-static:

  • static
  • non-static

I also feel that nested types should be kept to a minimum. All to often I see people having nested classes, enums, delegates that would be better of being a separate instance. There hardly ever is any gain of making a type nested. Put them in separate files as well. A file with 5 classes feels cluttered to me.

Shayn answered 1/12, 2021 at 9:53 Comment(0)
S
1

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.

Sculpin answered 29/9, 2008 at 20:26 Comment(2)
I use regions to separate by visibility as well, and having a Regionerate code layout keeps me honest. rauchy.net/regionerateHazeghi
I don't see a problem with using #regions, however I often find that as soon as I'm tempted to put in a region, it prompts me to consider splitting my classes up.Pember

© 2022 - 2024 — McMap. All rights reserved.