SBK1004: Contract.Requires used to validate a public argument

Analyzer SnowBank.Core
Severity Warning (correctness)
Code fix Yes

Message

Contract.Requires reports a bug in this code, not a bad argument from the caller. Use {0}, which throws the matching ArgumentException.

Why

Contract.Requires and Contract.Assert throw ContractException: the condition is one that the code itself guarantees, and a failure means a bug in the method. A bad argument from a caller is a different event: the caller expects ArgumentNullException or ArgumentOutOfRangeException, with the parameter name, so it can catch it or read it in a log.

The rule reports Contract.Requires(cond) or Contract.Assert(cond) in a public or protected member of a public type, when cond is p != null, p is not null, !string.IsNullOrEmpty(p), !string.IsNullOrWhiteSpace(p), p > 0, or p >= 0, and p is a parameter of that member. A private or internal member keeps Contract.Requires: that is the intended form for a helper whose callers are in the same assembly. A call with a custom message, or a condition on a local, a field, or a compound expression, is not reported. Neither is Contract.Debug.Requires or Contract.Debug.Assert: a Debug check is skipped in Release on purpose, on a path whose callers are trusted to pass valid arguments, and turning it into an argument check would add that cost back.

Bad

public void Register(string name, int count)
{
	Contract.Requires(name != null);
	Contract.Requires(count > 0);
}

Good

public void Register(string name, int count)
{
	Contract.NotNull(name);
	Contract.Positive(count);
}

Code fix

The fix rewrites the call by shape: Contract.NotNull(p), Contract.NotNullOrEmpty(p), Contract.NotNullOrWhiteSpace(p), Contract.Positive(p), or Contract.GreaterOrEqual(p, 0). The Positive and GreaterOrEqual forms are offered only for a parameter type the target overload accepts.

Suppress

#pragma warning disable SBK1004 // reason

or, for a whole project, in .editorconfig:

dotnet_diagnostic.SBK1004.severity = none