Search code examples
classvariablesmethodscoding-stylereadability

What is the best way to arrange variables and methods in a class?


I usually arrange my variables and methods like this:

class MyClass {
    // public variables
    // public methods
    // private methods
    // private variables
}

I want to know what is the best arrangement for defining functions and variables in terms of readability?

EDIT: Also what about enum and class definitions within the class?


Solution

  • Like this:

    class MyClass {
        // private fields
        // public methods
        // private methods
    }
    

    You shouldn't have any public fields. Use properties instead.

    StyleCop has a set of rules on suggested code order. See SA1201:

    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

    and SA1202:

    To comply with this rule, adjacent elements of the same type must be positioned in the following order by access level:

    • public
    • internal
    • protected internal
    • protected
    • private

    If you use StyleCop it will warn you when you break these rules.