Order of items in classes: Fields, Properties, Constructors, Methods

C#.NetCoding StyleCode CleanupCode Structure

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

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

Solution 5 - C#

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

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

Solution 6 - C#

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.

Solution 7 - C#

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

Solution 8 - C#

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.

Solution 9 - C#

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

Solution 10 - C#

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.

Solution 11 - C#

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.

Solution 12 - C#

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

Enumerations
Declarations
Constructors
Overrides
Methods
Properties
Event Handler

Solution 13 - C#

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

Solution 14 - C#

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?

Solution 15 - C#

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.

Solution 16 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmmcdoleView Question on Stackoverflow
Solution 1 - C#Jonathan WrightView Answer on Stackoverflow
Solution 2 - C#Ryan LundyView Answer on Stackoverflow
Solution 3 - C#brightView Answer on Stackoverflow
Solution 4 - C#WayneView Answer on Stackoverflow
Solution 5 - C#Elijah ManorView Answer on Stackoverflow
Solution 6 - C#Michael DamatovView Answer on Stackoverflow
Solution 7 - C#Mitchel SellersView Answer on Stackoverflow
Solution 8 - C#Aluan HaddadView Answer on Stackoverflow
Solution 9 - C#blowdartView Answer on Stackoverflow
Solution 10 - C#Rory BeckerView Answer on Stackoverflow
Solution 11 - C#WedgeView Answer on Stackoverflow
Solution 12 - C#PatView Answer on Stackoverflow
Solution 13 - C#user6630825View Answer on Stackoverflow
Solution 14 - C#Hamish SmithView Answer on Stackoverflow
Solution 15 - C#Jeff KotulaView Answer on Stackoverflow
Solution 16 - C#carlthecoderView Answer on Stackoverflow