Skip to content

Coding Rules

The style guide covers layout and naming. This page collects the common patterns we use across our repositories: errors, async work, threads, collections, trimming and comments. You do not need to memorise it before your first contribution. Our analysers enforce many of these rules and tell you at build time, and reviewers point out the rest.

Each repository's AGENTS.md can add more rules for that repository. Where the two differ, the repository's rules win.

Analyser warnings

Fix the code. Do not silence the warning.

  • Do not add #pragma warning disable, NoWarn, GlobalSuppressions files, or .editorconfig severity changes.
  • A [SuppressMessage] attribute needs a maintainer's agreement first. If you think a rule is wrong for your code, explain why in the pull request and ask.
  • Long lines, long methods and long files are fixed by wrapping or splitting them.

Guard clauses

Check arguments at public entry points with the .NET throw helpers, not hand-written if and throw blocks:

public void Add(string key, int count)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(key);
    ArgumentOutOfRangeException.ThrowIfNegative(count);
    ObjectDisposedException.ThrowIf(_disposed != 0, this);

    // ...
}
  • Guard public and protected members of public types, even when the parameter is not nullable. Callers with nullable warnings turned off can still pass null.
  • Private helpers called only from guarded members do not need their own guards.
  • Guard iterator and async methods in a plain wrapper method. Otherwise the check runs late, when the caller first enumerates or awaits.
  • On .NET Framework targets, use the helper or alias the repository already provides.

Async code

  • Never block on a task. No .Result, .Wait(), .GetAwaiter().GetResult() or Thread.Sleep, in product code or in tests.
  • Use ConfigureAwait(false) on every await in library code.
  • Do not write async void, except for a top-level event handler that catches its own exceptions.
  • Use Task.Run to move CPU work off a thread. Do not use Task.Factory.StartNew.
  • Take a CancellationToken as the last parameter, and pass it to every async call underneath.
  • Create a TaskCompletionSource with TaskCreationOptions.RunContinuationsAsynchronously.
  • Await a single task directly. Use Task.WhenAll and Task.WhenAny only for two or more tasks.
  • Wait for a condition with a bounded timeout, not a fixed delay.

Public API

  • Make types and members internal unless callers outside the assembly need them.
  • Seal classes unless they are designed to be inherited.
  • Never use InternalsVisibleTo between two shipping assemblies. It is for test assemblies only. To share code inside a repository, link the source file with Compile Include.
  • Every public change shows up in the PublicAPI.txt baselines. A removed or changed line is a breaking change and needs the break: commit type.
  • Name types, members and files after what they do, not after the change that added them.

Threads and locking

  • Use the repository's Lock alias for lock statements. It is System.Threading.Lock on modern .NET and object on .NET Framework.
  • Never lock (this), or lock on a public object or a Type.
  • Do not call user code, such as OnNext or a PropertyChanged handler, while holding a lock. Record what to send inside the lock and send it after releasing the lock.
  • Read fields that are written with Interlocked through Volatile.Read.

Disposal

  • Make Dispose safe to call twice and from two threads at once:

    public void Dispose()
    {
        if (Interlocked.Exchange(ref _disposed, 1) != 0)
        {
            return;
        }
    
        _subscription.Dispose();
    }
    
  • Throw ObjectDisposedException when a disposed object is used. Never throw from Dispose itself.

  • Dispose every subscription you create, or hand it to an owner that disposes it.

Collections and allocations

  • Use Dictionary and HashSet. Do not use frozen collections in libraries. A library cannot assume a long-running process that pays back their build cost.
  • Pass StringComparer.Ordinal for string keys.
  • Use TryGetValue instead of ContainsKey followed by the indexer.
  • Use concrete types such as List<T> and Dictionary<TKey, TValue> for fields, locals and internal returns. foreach over a concrete type does not allocate an enumerator.
  • Mark lambdas static when they capture nothing. Pass state through a TState parameter instead of capturing it.
  • Do not use LINQ in production code. The analysers enforce this. Use plain loops instead. LINQ is fine in test projects.
  • Measure with BenchmarkDotNet before claiming a change is faster.

Trimming and Native AOT

Libraries are checked by the trimming and AOT analysers, and trimming warnings are build errors.

  • Avoid reflection. Prefer source generators: JsonSerializerContext for JSON, [GeneratedRegex] for regular expressions, and [LoggerMessage] for logging.
  • Avoid Type.GetType(string), MakeGenericType and Activator.CreateInstance(Type).
  • Add [DynamicallyAccessedMembers] or [RequiresUnreferencedCode] only when no other design works.
  • APIs that need reflection belong in the .Unsafe packages.

Cross-platform code

Code must run on Windows, Linux and macOS.

  • Use managed .NET APIs. A P/Invoke or native library needs a maintainer's agreement first.
  • Guard calls that only work on some operating systems with OperatingSystem checks, for example OperatingSystem.IsWindows().

Comments and XML docs

  • Every public and protected member has an XML doc comment.
  • A <summary> is one sentence saying what the member does or returns, not how.
  • Document a <param> or <returns> only with something the signature does not say, such as units, valid ranges or what null means.
  • Add <remarks> only for unusual behaviour that covers the whole member. Put an inline // comment on a confusing statement instead.
  • Describe the code as it is. Do not describe how it used to work. Avoid words like "now", "previously", "no longer" and "used to".
  • Do not comment on code that is absent, such as why a flag is off or an idea was rejected.
Last updated Contributors: Glenn