[c#] Order of items in classes: Fields, Properties, Constructors, Methods

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?

This question is related to c# .net coding-style code-cleanup code-structure

The answer is


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


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

Enumerations
Declarations
Constructors
Overrides
Methods
Properties
Event Handler


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


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.


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.


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.


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


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


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.


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.


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.


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?


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)


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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to coding-style

Method Call Chaining; returning a pointer vs a reference? 80-characters / right margin line in Sublime Text 3 Cannot find reference 'xxx' in __init__.py - Python / Pycharm How to stick <footer> element at the bottom of the page (HTML5 and CSS3)? Simple way to create matrix of random numbers Is calling destructor manually always a sign of bad design? Count all values in a matrix greater than a value Iterate through a C++ Vector using a 'for' loop Which comment style should I use in batch files? Dictionaries and default values

Examples related to code-cleanup

Order of items in classes: Fields, Properties, Constructors, Methods How to identify unused CSS definitions from multiple CSS files in a project

Examples related to code-structure

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