Order of class members


Yeah, I know… there are lots of references online for this. And if you use StyleCop, you have a built-in way of ensuring consistent ordering.

However, I don’t use StyleCop (currently; I have in the past and I probably will again in the future), and I don’t like StyleCop’s recommended order. So here is mine:

First order by member type:

Constants
Fields
Enums
Delegates
Constructors
Finalizers
Properties
Indexers
Events
Operators
Methods
Nested Types

Within each type, by access modifier

public
internal
protected internal
protected
private

Then by static/instance

Static members
Instance members
Explicit Interface
         members

edit: Having laid this all out in writing, the first thing I do is, of course, a flip-flop. I have reversed the order from static/instance, then by access modifier to access modifier, then static/instance.

Why?

It occurred to me, while trying to get an overview of the methods in a class, that this ordering more closely follows C# syntax for declaring members (as in these examples)

public static readonly string VisibleConstantA;
public static readonly string VisibleConstantB;
private static readonly string HiddenConstantA;
private static readonly string HiddenConstantB;
private static readonly string HiddenConstantC;
private int _someInt;
private int _anotherInt;
public static void Method() {...}
public static void AnotherMethod() {...}
public void MethodName() {...}
private void MyMethod() {...}

When scrolling through a class’ members (especially when using Collapse to Definitions), having all the members with the same declarative text appear one above the other makes it easier to tell where you are in the file and where the member you are looking for may be located.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s