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,GlobalSuppressionsfiles, or.editorconfigseverity 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
asyncmethods 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()orThread.Sleep, in product code or in tests. - Use
ConfigureAwait(false)on everyawaitin library code. - Do not write
async void, except for a top-level event handler that catches its own exceptions. - Use
Task.Runto move CPU work off a thread. Do not useTask.Factory.StartNew. - Take a
CancellationTokenas the last parameter, and pass it to every async call underneath. - Create a
TaskCompletionSourcewithTaskCreationOptions.RunContinuationsAsynchronously. - Await a single task directly. Use
Task.WhenAllandTask.WhenAnyonly for two or more tasks. - Wait for a condition with a bounded timeout, not a fixed delay.
Public API¶
- Make types and members
internalunless callers outside the assembly need them. - Seal classes unless they are designed to be inherited.
- Never use
InternalsVisibleTobetween two shipping assemblies. It is for test assemblies only. To share code inside a repository, link the source file withCompile Include. - Every public change shows up in the
PublicAPI.txtbaselines. A removed or changed line is a breaking change and needs thebreak: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
Lockalias forlockstatements. It isSystem.Threading.Lockon modern .NET andobjecton .NET Framework. - Never
lock (this), or lock on a public object or aType. - Do not call user code, such as
OnNextor aPropertyChangedhandler, while holding a lock. Record what to send inside the lock and send it after releasing the lock. - Read fields that are written with
InterlockedthroughVolatile.Read.
Disposal¶
-
Make
Disposesafe to call twice and from two threads at once:public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) != 0) { return; } _subscription.Dispose(); } -
Throw
ObjectDisposedExceptionwhen a disposed object is used. Never throw fromDisposeitself. -
Dispose every subscription you create, or hand it to an owner that disposes it.
Collections and allocations¶
- Use
DictionaryandHashSet. Do not use frozen collections in libraries. A library cannot assume a long-running process that pays back their build cost. - Pass
StringComparer.Ordinalfor string keys. - Use
TryGetValueinstead ofContainsKeyfollowed by the indexer. - Use concrete types such as
List<T>andDictionary<TKey, TValue>for fields, locals and internal returns.foreachover a concrete type does not allocate an enumerator. - Mark lambdas
staticwhen they capture nothing. Pass state through aTStateparameter 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:
JsonSerializerContextfor JSON,[GeneratedRegex]for regular expressions, and[LoggerMessage]for logging. - Avoid
Type.GetType(string),MakeGenericTypeandActivator.CreateInstance(Type). - Add
[DynamicallyAccessedMembers]or[RequiresUnreferencedCode]only when no other design works. - APIs that need reflection belong in the
.Unsafepackages.
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
OperatingSystemchecks, for exampleOperatingSystem.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 whatnullmeans. - 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.