Question

C# Class Member Order: Organizing Fields, Properties, Constructors, and Methods

csharp.netcode-cleanupcode-structure

Question

Is there an official C# guideline that specifies the order of members within a class?

For example, should a class always be organized in this order?

public fields
private fields
properties
constructors
methods

Is there a strict rule for ordering fields, properties, constructors, and methods, or should a team choose and consistently follow its own convention?

Short Answer

C# does not require fields, properties, constructors, and methods to appear in a particular order. A consistent ordering convention improves readability and makes classes easier to scan, but the best convention is usually one your team documents and enforces with code reviews and tooling.

Concept

C# class members can generally be declared in any order. The compiler understands a class based on the names, types, and relationships of its members—not on whether a constructor appears before a property.

For example, this is valid even though the constructor uses a field declared later:

public class Counter
{
    public Counter(int start)
    {
        _value = start;
    }

    private int _value;
}

Although member order does not change correctness, it affects human readability. When every class follows a familiar structure, developers can quickly find:

  • dependencies stored in fields,
  • public information exposed by properties,
  • ways to create the object,
  • public behavior, and
  • private implementation details.

There is no single mandatory, language-level order. Microsoft’s C# coding conventions discuss many style choices, but a project can reasonably adopt a different member layout when it is documented and consistently applied.

A useful general principle is: organize code so related members are easy to find and understand. Consistency matters more than choosing one supposedly perfect order.

Mental Model

Think of a class as a well-organized instruction manual.

  • Fields are the private notes and supplies the class keeps nearby.
  • Properties are the labeled controls other code can use.
  • Constructors are the setup instructions for creating the object.
  • Methods are the actions the object can perform.

A reader should be able to open the manual and locate each category without searching through unrelated pages. The exact table of contents is less important than using the same one throughout the project.

Also, keep closely connected items together. A private helper method may be easier to understand near the public method it supports than in a distant block containing every private method in the class.

Take Quiz

Syntax and Examples

A common C# convention is to put the class’s externally useful API near the top and implementation details lower down:

public class BankAccount
{
    // Fields
    private decimal _balance;

    // Properties
    public string AccountNumber { get; }
    public decimal Balance => _balance;

    // Constructor
    public BankAccount(string accountNumber, decimal openingBalance)
    {
        AccountNumber = accountNumber;
        _balance = openingBalance;
    }

    // Public methods
    public void Deposit(decimal amount)
    {
        if (amount <= 0)
        {
            throw new ArgumentOutOfRangeException(nameof(amount));
        }

        _balance += amount;
    }

    public bool TryWithdraw(decimal amount)
    {
        if (amount <= 0 || amount > _balance)
        {
            return false;
        }

        _balance -= amount;
        return true;
    }
}

This arrangement lets a reader answer common questions quickly:

  1. What state does this object store? _balance.
  2. What can callers read? AccountNumber and Balance.
  3. How is it created? BankAccount(...).
  4. What can it do? Deposit and TryWithdraw.

Some teams put constructors before properties, and some group public members before private members. Both are valid if the team applies the decision consistently.

Step by Step Execution

Consider this class layout:

public class Temperature
{
    private double _celsius;

    public double Celsius => _celsius;

    public Temperature(double celsius)
    {
        _celsius = celsius;
    }

    public double ToFahrenheit()
    {
        return (_celsius * 9 / 5) + 32;
    }
}

When this code runs:

var temperature = new Temperature(20);
double fahrenheit = temperature.ToFahrenheit();

The execution is:

  1. new Temperature(20) calls the constructor.
  2. The constructor assigns 20 to the private _celsius field.
  3. temperature.ToFahrenheit() calls the public method.
  4. The method reads _celsius, calculates (20 * 9 / 5) + 32, and returns 68.
  5. fahrenheit receives 68.

The member order makes this story easy to follow, but moving ToFahrenheit above the constructor would not change the result. Ordering is for people reading the source code, not for changing runtime behavior.

Real World Use Cases

A predictable member order helps in many everyday C# projects:

  • ASP.NET Core controllers: Place injected service fields, the constructor, public action methods, then private helper methods in a recognizable layout.
  • Domain models: Put identity and public properties near the top, then domain operations such as Cancel, Approve, or AddItem.
  • API clients: Group configuration fields and constructors together, expose public request methods, and keep request-building helpers private.
  • Background services: Show dependencies and startup configuration first, followed by the main execution method and private processing helpers.
  • Desktop or game applications: Group event declarations, properties, constructors, and event-handler methods consistently so maintenance is faster.

The aim is not merely visual tidiness. Familiar structure reduces the time needed to inspect, review, debug, and modify a class.

Take Quiz

Real Codebase Usage

In real codebases, teams usually combine a member-order convention with a few practical patterns.

Keep dependencies and construction visible

Constructor-injected dependencies are commonly placed near the top:

public class OrderService
{
    private readonly IOrderRepository _orders;
    private readonly ILogger<OrderService> _logger;

    public OrderService(IOrderRepository orders, ILogger<OrderService> logger)
    {
        _orders = orders;
        _logger = logger;
    }
}

This makes it clear what the class needs to do its work.

Put the public API before implementation details

Callers care about public members. Many teams place public methods first and private helpers afterward:

public class EmailValidator
{
    public bool IsValid(string? email)
    {
        if (string.IsNullOrWhiteSpace(email))
        {
            return false;
        }

        return HasAtSign(email) && HasDomain(email);
    }

    private static bool HasAtSign(string email) => email.Contains('@');

    private static bool HasDomain(string email) => email.EndsWith(".com", StringComparison.OrdinalIgnoreCase);
}

Use guard clauses within methods

Member ordering is separate from method structure, but both improve scanability. Guard clauses handle invalid cases early and keep the main path clear.

Enforce only what helps

Use .editorconfig, IDE formatting, analyzers, and code reviews to standardize formatting and naming. Member ordering is not fully standardized by the C# compiler, so teams may use analyzer packages or review conventions if they want automated checks. Avoid creating rules so detailed that they make related code harder to keep together.

Common Mistakes

Treating a preferred order as a C# compiler rule

This is false: the compiler does not require constructors, fields, or methods to appear in a fixed sequence.

public class ValidClass
{
    public void Run() { }

    private int _count;

    public ValidClass()
    {
        _count = 0;
    }
}

This compiles. Do not reject code only because it differs from a convention unless your project has explicitly adopted that convention.

Exposing mutable public fields

A layout such as “public fields first” can accidentally normalize public fields. In most application code, prefer properties or methods because they allow validation and can protect object state.

// Usually avoid this.
public decimal Balance;

// Prefer a controlled public view.
public decimal Balance { get; private set; }

Separating related code too aggressively

Putting every private method at the bottom is often fine, but it can make a class difficult to read when a public method depends on several helpers. Keep a coherent group together when that tells the story better.

Inconsistent ordering between files

A convention only helps if readers can rely on it. Document a small rule set and use it consistently rather than changing the layout based on personal preference in every file.

Using regions to hide a poorly designed class

Many large #region blocks can make navigation harder and may signal that a class has too many responsibilities. Consider extracting focused classes instead of adding more categories to an oversized class.

Reordering code without considering static initialization

Most member rearrangement is behavior-neutral, but field initializers can have observable order. Be careful when fields initialize values with method calls or side effects.

private readonly string _first = Create("first");
private readonly string _second = Create("second");

Changing these declarations can change the order in which Create is called during object construction.

Comparisons

ApproachStrengthsLimitationsGood fit
Group by member kindEasy to scan: fields, properties, constructors, then methodsRelated behavior can be far from its helpersSmall and medium application classes
Public API first, private details laterReaders see how to use the class immediatelyMay split fields from the methods that use themLibraries, services, and reusable components
Group by feature or behaviorKeeps a public operation near its private helpersCategories are less uniform across the fileClasses with several distinct operations
Strict analyzer-enforced orderReduces review debates and keeps files uniformCan become rigid or require tool configurationLarge teams with established standards
No documented conventionMaximum individual freedomHarder navigation and more style discussionUsually not ideal for shared codebases

A practical compromise is:

  1. Keep fields and constructors near the top.
  2. Keep public API easy to find.
  3. Put private helpers after the public methods, unless keeping a helper close to its feature is clearer.
  4. Use the same pattern throughout the project.
Take Quiz

Cheat Sheet

  • C# has no required compiler-enforced order for class members.
  • Choose a team convention and apply it consistently.
  • A common layout is:
public class Example
{
    // Constants and static fields
    // Instance fields
    // Constructors
    // Properties and events
    // Public methods
    // Private helper methods
}
  • Another valid layout places properties before constructors.
  • Prefer private fields plus public properties or methods over mutable public fields.
  • Put readonly dependencies near the constructor that receives them.
  • Keep related members together when that improves comprehension.
  • Use code review, .editorconfig, and analyzers for shared style rules.
  • Take care when reordering field initializers with side effects: declaration order may affect behavior.

FAQ

Is there an official required order for members in a C# class?

No. C# allows fields, properties, constructors, methods, and nested types in various orders. The compiler does not impose a general class-member ordering rule.

Should C# fields be public or private?

Most fields should be private. Expose data through properties or methods when outside code needs access, because this preserves control over validation and future changes.

Should constructors come before properties in C#?

Either order is valid. Choose the ordering used by your existing project or team. Consistency is more useful than the specific choice.

Does member order affect C# performance?

Ordinary source ordering does not provide a meaningful performance benefit. It is primarily a readability and maintenance concern.

Can a C# constructor use a field declared later in the file?

Yes. Members of a class are available throughout that class regardless of where their declarations appear. Field initializer order is a separate concern when initializers have side effects.

How can a team enforce C# member ordering?

Document the convention, apply it in code review, and optionally configure IDE tooling or analyzer rules that support the chosen style. The appropriate tool depends on the project’s existing toolchain.

Should private helper methods always be at the bottom of a class?

Often, but not always. Putting them after public methods is a common convention. Keep them close to the feature they support if that makes the code easier to follow.

Take Quiz

Mini Project

Description

Create a small TaskList class with a predictable member layout. The class represents a simple in-memory task tracker and demonstrates private state, a public read-only property, construction, public operations, and private validation helpers.

Goal

Build a TaskList class that adds and completes task items while keeping its members organized using one consistent C# convention.

Requirements

Requirement 1

Take Quiz

Keep learning

Related questions

View more