Question

Is there a standard way to organize methods within a class?

There seem to be many different ways of organizing methods in a class. I could group methods by access, and order them alphabetically. I could group related methods together. I could use a mix of the two, or something else entirely. Is there a standard way to approach this? If not, how do you approach it?

 45  26910  45
1 Jan 1970

Solution

 54

StyleCop enforces some things here:

Within a class, struct, or interface, elements must be positioned in the following order:

  • Fields
  • Constructors
  • Finalizers (Destructors)
  • Delegates
  • Events
  • Enums
  • Interfaces
  • Properties
  • Indexers
  • Methods
  • Structs
  • Classes

Furthermore, elements are ordered by access:

  • public
  • internal
  • protected internal
  • protected
  • private

As well as a few other rules:

  • Contants have to appear before fields
  • static elements have to appear before instance elements.

This might be a good baseline to start. As for additional ordering rules, I usually group related methods together.

2010-01-28

Solution

 7

Whatever you do, put it in your standards and be consistent. We use a custom Regionerate configuration to order our methods. Everyone on the team uses the same configuration.

EDIT: We're now using ReSharper's Code Cleanup with a custom Type Members Layout.

2010-01-28