788

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?

4
  • 8
    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. Apr 28, 2013 at 22:15
  • 2
    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.
    – nawfal
    May 20, 2013 at 20:04
  • 36
    This question isn't opinion-based, as it asks whether there's an official guideline. Either there is a guideline or there isn't! Jun 3, 2014 at 4:24
  • 2
    @nawfal 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 too Mar 2, 2020 at 17:43

16 Answers 16

1219

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.

24
  • 45
    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.
    – Kenny Mann
    Mar 24, 2009 at 19:49
  • 56
    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. Mar 26, 2009 at 0:56
  • 20
    I liked the partial class tip Jan 19, 2012 at 20:41
  • 12
    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.
    – Nope
    Apr 30, 2012 at 13:36
  • 5
    @FrançoisWahl Is the overhead associated with the compiler combining partial classes into a single type that large?
    – dav_i
    Sep 4, 2012 at 9:14
48

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

6
  • 3
    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)
    – hfrmobile
    Aug 14, 2012 at 8:12
  • 95
    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?
    – Ryan Lundy
    Aug 14, 2012 at 13:24
  • 14
    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? Feb 15, 2013 at 10:06
  • 13
    +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. Apr 28, 2013 at 21:49
  • 91
    grouping by functionality is called a class
    – MrDosu
    Jul 11, 2013 at 11:11
32

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.

5
  • 3
    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.
    – David Culp
    May 29, 2015 at 15:22
  • 2
    Actually, the order they tend to be looked for by humans, the notion of literary programming that code should first be readable by humans.
    – bright
    Oct 19, 2015 at 4:56
  • 2
    Note that primary constructors were removed from the plans for C# 6: stackoverflow.com/a/26915809/5085211
    – fuglede
    Oct 11, 2016 at 14:10
  • 6
    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.
    – Matt Davis
    Mar 15, 2017 at 18:25
  • maybe for classes with code, and just maybe, but for the classes that contains only data first thing i want to see are properties/fields
    – lunadir
    Jan 28 at 21:28
26

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

3
  • This is exactly how I do it as well. Except between Class and Private Members, I have any Public Constants and Enums etc.
    – deegee
    Jan 7, 2016 at 23:11
  • 1
    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 unit
    – zameb
    Dec 7, 2018 at 20:10
  • 4
    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.
    – ssmith
    Feb 14, 2021 at 22:34
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)

2
  • 3
    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 #justsaying
    – Liam
    May 13, 2015 at 9:56
  • 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.
    – Pablo H
    Feb 18, 2019 at 12:35
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

5
  • 28
    Here is to say (just for information) that stylecop does recommend not using regions (SA1124 DoNotUseRegions)
    – Gerwald
    Jan 19, 2012 at 15:43
  • 3
    Microsoft itself is using regions.
    – zwcloud
    Mar 15, 2018 at 4:53
  • 3
    @zwcloud Sure, in a file with 5538 lines, regions are necessary, but that doesn't mean you should use regions in normal files.
    – Ghost4Man
    May 27, 2018 at 10:49
  • 1
    @Gerwald: I think StyleCop is only for people using StyleCop. It is one out of many standards
    – zameb
    Dec 7, 2018 at 20:16
  • 1
    @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.
    – Gerwald
    Dec 14, 2018 at 15:48
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.

7

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

protected delegates
protected interfaces
protected classes
protected structs

private delegates
private interfaces
private classes
private structs

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.

3
  • 5
    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.
    – Matt Davis
    Mar 15, 2017 at 18:28
  • 1
    That actually makes a lot of sense. I bet it is a holdover from C. Mar 15, 2017 at 18:30
  • 1
    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 anyway
    – Ryan Leach
    Apr 24, 2018 at 5:14
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

5
  • Interesting. Do you use StyleCop regularly?
    – mmcdole
    Sep 29, 2008 at 21:09
  • For one project yes, because it does get used for some MS contract work now and again. It's very annoying grin
    – blowdart
    Sep 29, 2008 at 21:27
  • 1
    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)
    – hfrmobile
    Aug 14, 2012 at 8:11
  • 1
    According to StyleCop public fields should go before private fields stylecop.com/docs/SA1202.html Apr 28, 2013 at 21:16
  • 1
    What do you mean by "StyleCop is part of the MS build process"? Is microsoft using StyleCop for all its code?
    – Rico Suter
    Sep 25, 2014 at 14:50
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.

0
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.

3

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

Enumerations
Declarations
Constructors
Overrides
Methods
Properties
Event Handler

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; }
}
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?

1
  • 3
    and once you need regions... you have lost. Oct 29, 2012 at 23:14
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.

2
  • I use regions to separate by visibility as well, and having a Regionerate code layout keeps me honest. rauchy.net/regionerate Sep 29, 2008 at 20:28
  • 1
    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.
    – mikecamimo
    Feb 22, 2018 at 2:08
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.