fluentcontracts
Write and apply FluentContracts argument validation in C#. Use when adding or reviewing guard clauses, argument checks, parameter validation or precondition checks in a .NET codebase — replacing hand-written `if (x == null) throw new ArgumentNullException(...)` blocks with `x.Must()` chains, choosing the right check, writing failure messages, or adding a reusable rule as an `ISpecification<T>`. Also use when the project already references the FluentContracts NuGet package and new code needs guards that match it.
FluentContracts · 已有静态检查记录
安装与使用
运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。
npx skills add FluentContracts/FluentContracts --skill fluentcontracts技能说明
name: fluentcontracts
description: Write and apply FluentContracts argument validation in C#. Use when adding or reviewing guard clauses, argument checks, parameter validation or precondition checks in a .NET codebase — replacing hand-written if (x == null) throw new ArgumentNullException(...) blocks with x.Must() chains, choosing the right check, writing failure messages, or adding a reusable rule as an ISpecification<T>. Also use when the project already references the FluentContracts NuGet package and new code needs guards that match it.
Apply FluentContracts in C# code
FluentContracts replaces hand-written guard clauses with one readable chain that throws the right exception, names the argument and says what was expected.
public void AddOrder(Order myOrder)
{
myOrder.Must().NotBeNull().Satisfy<Order>(o => o.Quantity >= 5, "Quantity cannot be less than 5");
}
Before you write a check, confirm it exists
Do not invent a check name. The library has a large but finite surface, and a guessed name is a compile error at best and the wrong assertion at worst.
- In the editor, type
value.Must().and read IntelliSense — the package ships XML documentation for every public member, so the list is authoritative for the version the project actually references. - On the command line or from a repository, the generated catalogue of every
contract and every check is
docs/SupportedContracts.md. It is produced by reflection over the built assembly, so it is the complete list, and it tracksmaster— a check listed there may not be in the version the project has pinned. - The naming system and the rules that decide overloads, messages and
exception types are in
references/cheatsheet.md. Read it before writing more than a single check.
If no check fits, do not reach for a raw if/throw next to a chain — use
Satisfy or a specification (below). Both fail through the same machinery, so
the message and the argument name still come out right.
Adding it to a project
dotnet add package FluentContracts
netstandard2.0 and net8.0, no runtime dependencies. Then using FluentContracts;
— Must() is an extension method, and every contract type is reached through it.
The shape of a guard
Start with Must(). It captures the argument's name at the call site through
[CallerArgumentExpression], so there is no nameof to keep in sync, and it
returns the contract for the argument's static type — int gets IntContract,
string gets StringContract, IList<T> gets ListContract<T>, and so on.
Chain the checks. Every check returns the same contract, so checks follow one
another directly. .And. is an identity property kept only for reading; use it
when it helps a long chain and leave it out otherwise.
public void Connect(string host, int port, IList<string> fallbacks)
{
host.Must().NotBeNullOrWhiteSpace().And.NotBeMatching(@"\s");
port.Must().BeBetween(1, 65535);
fallbacks.Must().NotBeNull().NotBeEmpty().NotContainNull();
}
End with Value() when the guard and the read are the same statement. It
returns the unwrapped, non-nullable value and fails a null argument with
ArgumentNullException exactly as NotBeNull would — so x.Must().Value() on
its own is a complete null guard.
this.port = config.Port.Must().BeBetween(1, 65535).Value();
this.host = config.Host.Must().NotBeNullOrEmpty().Value();
This is the idiom to prefer in a constructor: it collapses the guard and the
assignment, and it removes the nullable warning at the field without a !.
Messages
The message parameter is always last, after every operand, and it replaces
the default message for that check. It may use {argument} and {value}, which
are filled in on the failure path:
port.Must().BeBetween(1, 65535, "{argument} must be a usable port, got {value}");
A message for the whole chain goes to Must() as its first argument. A
check's own message still wins for that check:
environment.Must("This should be prod").NotBe("test").NotBeEmpty();
Write the default message first — it already names the argument, the expectation and the actual value, and it is usually better than a hand-written one. Add a message only when the domain reason is not obvious from the check itself ("must be a usable port"), not to restate the check ("must be between 1 and 65535").
The one overload trap
A check that takes several candidate values has exactly three overloads — one
value, a set, and a set followed by a message — and never params:
status.Must().BeAnyOf("draft"); // one value
status.Must().BeAnyOf(["draft", "published"]); // a set
status.Must().BeAnyOf(["draft", "published"], "unknown status"); // a set, then the message
So a message only ever follows a bracketed set. BeAnyOf("draft", "published")
does not compile — deliberately, because on a string it would otherwise bind
"published" as the message and silently check the wrong thing.
Fixed-arity checks are unambiguous and keep (operands…, message) with no
brackets: NotBe("test", "This should be prod"), BeBetween(1, 65535, "…").
Which exception you get
Pick the check that matches what you are asserting and the exception follows; do not try to steer it.
| You get | For |
|---|---|
ArgumentNullException | a null argument — NotBeNull, Value(), and the implicit null check in Satisfy |
ArgumentOutOfRangeException | ordinal checks only — comparisons, ranges, sign, the NaN policy |
ArgumentException | everything else |
Null and NaN. Ordering comparisons (BeGreaterThan, BeLessThan, BeBetween,
BePositive, BeNegative, …) reject `null