ChatGPT解决这个技术问题 Extra ChatGPT

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?

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.
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.
This question isn't opinion-based, as it asks whether there's an official guideline. Either there is a guideline or there isn't!
@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

B
BurnsBA

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.


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.
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.
I liked the partial class tip
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.
@FrançoisWahl Is the overhead associated with the compiler combining partial classes into a single type that large?
R
Ryan Lundy

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


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)
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?
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?
+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.
grouping by functionality is called a class
b
bright

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.


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.
Actually, the order they tend to be looked for by humans, the notion of literary programming that code should first be readable by humans.
Note that primary constructors were removed from the plans for C# 6: stackoverflow.com/a/26915809/5085211
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.
@DavidCulp: i think he didn't mean to say that he wants to see in what order a class is initialized, he is not a compiler but a human. He wants to "understand how this object is constructed", which is understandable. He might need this class and wants to see the dependencies and what it really needs.
W
Wayne

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 exactly how I do it as well. Except between Class and Private Members, I have any Public Constants and Enums etc.
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
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.
E
Elijah Manor

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)


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
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.
M
Michael Damatov

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.


M
Mitchel Sellers

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


Here is to say (just for information) that stylecop does recommend not using regions (SA1124 DoNotUseRegions)
@zwcloud Sure, in a file with 5538 lines, regions are necessary, but that doesn't mean you should use regions in normal files.
@Gerwald: I think StyleCop is only for people using StyleCop. It is one out of many standards
@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.
A
Aluan Haddad

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.


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.
That actually makes a lot of sense. I bet it is a holdover from C.
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
b
blowdart

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


Interesting. Do you use StyleCop regularly?
For one project yes, because it does get used for some MS contract work now and again. It's very annoying grin
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)
According to StyleCop public fields should go before private fields stylecop.com/docs/SA1202.html
What do you mean by "StyleCop is part of the MS build process"? Is microsoft using StyleCop for all its code?
R
Rory Becker

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.


C
Community

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.


P
Pat

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

Enumerations Declarations Constructors Overrides Methods Properties Event Handler


佚名

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

H
Hamish Smith

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?


and once you need regions... you have lost.
J
Jeff Kotula

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 use regions to separate by visibility as well, and having a Regionerate code layout keeps me honest. rauchy.net/regionerate
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.
c
carlthecoder

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.