Skip to content

OnixLabs.Core.Preconditions

Matthew Layton edited this page Nov 15, 2026 · 2 revisions

Preconditions Class

Provides general guard-clause helpers for enforcing pre-conditions on arguments and state, throwing a well-typed exception when a condition is not met.

Namespace OnixLabs.Core
Assembly OnixLabs.Core.dll (NuGet)
Inheritance object → Preconditions

Definition

public static class Preconditions

Remarks

Preconditions collects the validation idioms used throughout ONIXLabs into a single static class. The members are grouped by the exception they raise, using C# 14 static extension members declared on the relevant exception type:

  • Members declared on InvalidOperationException — the Check… family — guard state and throw InvalidOperationException.
  • Members declared on ArgumentException — the Require and RequireIs…/RequireNotNullOr… family — guard arguments and throw ArgumentException.
  • Members declared on ArgumentNullException — RequireNotNull — guard against null arguments and throw ArgumentNullException.
  • Members declared on ArgumentOutOfRangeException — RequireWithinRange… and RequireIsDefined — guard ranges and enum values and throw ArgumentOutOfRangeException.

The class participates in a global using static OnixLabs.Core.Preconditions within the library, so the helpers are typically called unqualified, for example RequireNotNull(value) or Check(condition). Consumers can enable the same convenience with a using static OnixLabs.Core.Preconditions; directive.

Key behaviours:

  • Check… versus Require… — semantically, Check… validates state (failure indicates an invalid operation), whereas Require… validates arguments (failure indicates a caller-supplied bad value). This is reflected in the exception type each throws.
  • CallerArgumentExpression — every Require… member captures the caller's argument expression text into its parameterName parameter automatically (unless an explicit value is supplied), so the thrown ArgumentException / ArgumentNullException / ArgumentOutOfRangeException reports the offending expression. The Check… members do not capture a parameter name, because they validate state rather than a named argument.
  • [NotNull] flow analysis — the null-guarding members annotate their value parameter with [NotNull], so after a successful call the compiler treats the value as non-null. These members also return the non-null value, enabling fluent assignment such as Some<T> Some(T value) => new(RequireNotNull(value));.
  • Narrowing returns — the …IsFailure, …IsSuccess, …IsNone and …IsSome members return the value cast to the asserted concrete type (Failure, Success<T>, None<T>, and so on), so a single call both validates and narrows.
  • Lazy interpolated messages — Check and Require have overloads that take a PreconditionInterpolatedStringHandler. When the message is an interpolated string, the compiler selects these overloads automatically and passes the condition to the handler, so the message is only formatted when the condition is false. No code changes are needed. Because the holes are not evaluated when the check passes, any side effects inside the {…} holes only run when the check fails.

Examples

Guarding arguments

using OnixLabs.Core;
using static OnixLabs.Core.Preconditions;

public Order CreateOrder(string reference, int quantity)
{
    // Throws ArgumentNullException with parameterName "reference" if null.
    string validReference = RequireNotNull(reference);

    // Throws ArgumentException with parameterName "reference" if empty/whitespace.
    RequireNotNullOrWhiteSpace(reference);

    // Throws ArgumentOutOfRangeException with parameterName "quantity" if out of range.
    int validQuantity = RequireWithinRangeInclusive(quantity, 1, 100);

    return new Order(validReference, validQuantity);
}

Guarding state

using static OnixLabs.Core.Preconditions;

public void Ship(Order order)
{
    // Throws InvalidOperationException if the condition is false.
    Check(order.IsPaid, "Order must be paid before it can be shipped.");

    // The interpolated message is only formatted if the check fails.
    Check(order.Lines.Count > 0, $"Order '{order.Reference}' has no lines.");
}

Validating and narrowing a Result or Optional

using OnixLabs.Core;
using static OnixLabs.Core.Preconditions;

Result<int> result = Result<int>.Of(() => Compute());

// Narrows to Success<int>, or throws ArgumentException if it is a Failure<int>.
Success<int> success = RequireIsSuccess(result);
int value = success.Value;

Optional<string> optional = Optional<string>.Of("hello");

// Narrows to Some<string>, or throws ArgumentException if it is None<string>.
Some<string> some = RequireIsSome(optional);

Validating an enum argument

using static OnixLabs.Core.Preconditions;

public enum Direction { North, South, East, West }

public void Move(Direction direction)
{
    // Throws ArgumentOutOfRangeException if direction is not a defined member.
    RequireIsDefined(direction);
}

Methods

All members are static. They are grouped below by the exception type they throw.

Methods that throw InvalidOperationException

Method Returns Description
Check(bool, string) void Fails when the specified condition is false.
Check(bool, ref PreconditionInterpolatedStringHandler) void Fails when the specified condition is false; the interpolated message is only formatted on failure.
CheckIsFailure(Result, string) Failure Fails when the Result is not a Failure.
CheckIsSuccess(Result, string) Success Fails when the Result is not a Success.
CheckIsFailure<T>(Result<T>, string) Failure<T> Fails when the Result<T> is not a Failure<T>.
CheckIsSuccess<T>(Result<T>, string) Success<T> Fails when the Result<T> is not a Success<T>.
CheckIsNone<T>(Optional<T>, string) None<T> Fails when the Optional<T> is not a None<T>.
CheckIsSome<T>(Optional<T>, string) Some<T> Fails when the Optional<T> is not a Some<T>.
CheckNotNull<T>(T?, string) T Fails when the reference-type value is null.
CheckNotNull<T>(T?, string) (struct) T Fails when the nullable value type is null.
CheckNotNullOrEmpty(string?, string) string Fails when the string is null or empty.
CheckNotNullOrWhiteSpace(string?, string) string Fails when the string is null or whitespace.

Methods that throw ArgumentException

Method Returns Description
Require(bool, string, string?) void Fails when the specified condition is false.
Require(bool, ref PreconditionInterpolatedStringHandler, string?) void Fails when the specified condition is false; the interpolated message is only formatted on failure.
RequireIsFailure(Result, string, string?) Failure Fails when the Result is not a Failure.
RequireIsSuccess(Result, string, string?) Success Fails when the Result is not a Success.
RequireIsFailure<T>(Result<T>, string, string?) Failure<T> Fails when the Result<T> is not a Failure<T>.
RequireIsSuccess<T>(Result<T>, string, string?) Success<T> Fails when the Result<T> is not a Success<T>.
RequireIsNone<T>(Optional<T>, string, string?) None<T> Fails when the Optional<T> is not a None<T>.
RequireIsSome<T>(Optional<T>, string, string?) Some<T> Fails when the Optional<T> is not a Some<T>.
RequireNotNullOrEmpty(string?, string, string?) string Fails when the string is null or empty.
RequireNotNullOrWhiteSpace(string?, string, string?) string Fails when the string is null or whitespace.

Methods that throw ArgumentNullException

Method Returns Description
RequireNotNull<T>(T?, string, string?) T Fails when the reference-type value is null.
RequireNotNull<T>(T?, string, string?) (struct) T Fails when the nullable value type is null.

Methods that throw ArgumentOutOfRangeException

Method Returns Description
RequireWithinRangeInclusive<T>(T, T, T, string, string?) T Fails when the value is outside the inclusive range.
RequireWithinRangeExclusive<T>(T, T, T, string, string?) T Fails when the value is outside the exclusive range.
RequireIsDefined<T>(T, string?) T Fails when the value is not a defined member of the Enum type.

Check(bool, string)

public static void Check(bool condition, string message = "Argument must satisfy the specified condition.")

Performs a general pre-condition check that fails when the specified condition is false.

Parameter Type Description
condition bool The condition to check.
message string The exception message to throw when condition is false.

Exceptions

Exception Condition
InvalidOperationException condition is false.

Check(bool, ref PreconditionInterpolatedStringHandler)

public static void Check(
    bool condition,
    [InterpolatedStringHandlerArgument(nameof(condition))] ref PreconditionInterpolatedStringHandler message)

Performs a general pre-condition check that fails when the specified condition is false. The compiler selects this overload when message is an interpolated string, and passes condition to the PreconditionInterpolatedStringHandler, so the message is only formatted when condition is false.

Parameter Type Description
condition bool The condition to check.
message ref PreconditionInterpolatedStringHandler The interpolated exception message to throw when condition is false, which is only formatted when condition is false.

Exceptions

Exception Condition
InvalidOperationException condition is false.
// order.Reference is only read, and the message only built, when the check fails.
Check(order.IsPaid, $"Order '{order.Reference}' must be paid before it can be shipped.");

CheckIsFailure(Result, string)

public static Failure CheckIsFailure(Result result, string message = "Argument must be a Failure state.")

Checks that the specified Result is a Failure.

Parameter Type Description
result Result The current Result to check.
message string The exception message to throw when result is not a Failure.

Returns — The result cast to Failure.

Exceptions

Exception Condition
InvalidOperationException result is not of type Failure.

CheckIsSuccess(Result, string)

public static Success CheckIsSuccess(Result result, string message = "Argument must be a Success state.")

Checks that the specified Result is a Success.

Parameter Type Description
result Result The current Result to check.
message string The exception message to throw when result is not a Success.

Returns — The result cast to Success.

Exceptions

Exception Condition
InvalidOperationException result is not of type Success.

CheckIsFailure<T>(Result<T>, string)

public static Failure<T> CheckIsFailure<T>(Result<T> result, string message = "Argument must be a Failure state.")

Checks that the specified Result<T> is a Failure<T>.

Parameter Type Description
result Result<T> The current Result<T> to check.
message string The exception message to throw when result is not a Failure<T>.
Type Parameter Description
T The underlying type of the Result<T> instance.

Returns — The result cast to Failure<T>.

Exceptions

Exception Condition
InvalidOperationException result is not of type Failure<T>.

CheckIsSuccess<T>(Result<T>, string)

public static Success<T> CheckIsSuccess<T>(Result<T> result, string message = "Argument must be a Success state.")

Checks that the specified Result<T> is a Success<T>.

Parameter Type Description
result Result<T> The current Result<T> to check.
message string The exception message to throw when result is not a Success<T>.
Type Parameter Description
T The underlying type of the Result<T> instance.

Returns — The result cast to Success<T>.

Exceptions

Exception Condition
InvalidOperationException result is not of type Success<T>.

CheckIsNone<T>(Optional<T>, string)

public static None<T> CheckIsNone<T>(Optional<T> optional, string message = "Argument must be a None<T> value.")
    where T : notnull

Checks that the specified Optional<T> is a None<T>.

Parameter Type Description
optional Optional<T> The current Optional<T> to check.
message string The exception message to throw when optional is not a None<T>.
Type Parameter Description
T The underlying type of the Optional<T> instance. Must be non-nullable.

Returns — The optional cast to None<T>.

Exceptions

Exception Condition
InvalidOperationException optional is not of type None<T>.

CheckIsSome<T>(Optional<T>, string)

public static Some<T> CheckIsSome<T>(Optional<T> optional, string message = "Argument must be a Some<T> value.")
    where T : notnull

Checks that the specified Optional<T> is a Some<T>.

Parameter Type Description
optional Optional<T> The current Optional<T> to check.
message string The exception message to throw when optional is not a Some<T>.
Type Parameter Description
T The underlying type of the Optional<T> instance. Must be non-nullable.

Returns — The optional cast to Some<T>.

Exceptions

Exception Condition
InvalidOperationException optional is not of type Some<T>.

CheckNotNull<T>(T?, string)

public static T CheckNotNull<T>([NotNull] T? value, string message = "Argument must not be null.")

Checks that the specified reference-type value is not null. This overload applies to reference types.

Parameter Type Description
value T? The nullable value to check.
message string The exception message to throw when value is null.
Type Parameter Description
T The underlying type of the value.

Returns — The non-null value.

Exceptions

Exception Condition
InvalidOperationException value is null.

CheckNotNull<T>(T?, string) (struct)

public static T CheckNotNull<T>([NotNull] T? value, string message = "Argument must not be null.")
    where T : struct

Checks that the specified nullable value-type value is not null. This overload applies to value types via the where T : struct constraint, accepting Nullable<T>.

Parameter Type Description
value T? The nullable value to check.
message string The exception message to throw when value is null.
Type Parameter Description
T The underlying value type. Must be a struct.

Returns — The non-null value.

Exceptions

Exception Condition
InvalidOperationException value is null.

CheckNotNullOrEmpty(string?, string)

public static string CheckNotNullOrEmpty([NotNull] string? value, string message = "Argument must not be null or empty.")

Checks that the specified string is neither null nor empty.

Parameter Type Description
value string? The string value to check.
message string The exception message to throw when value is null or empty.

Returns — The non-null, non-empty value.

Exceptions

Exception Condition
InvalidOperationException value is null or an empty string.

CheckNotNullOrWhiteSpace(string?, string)

public static string CheckNotNullOrWhiteSpace([NotNull] string? value, string message = "Argument must not be null or whitespace.")

Checks that the specified string is neither null nor whitespace.

Parameter Type Description
value string? The string value to check.
message string The exception message to throw when value is null or whitespace.

Returns — The non-null, non-whitespace value.

Exceptions

Exception Condition
InvalidOperationException value is null or consists only of whitespace.

Require(bool, string, string?)

public static void Require(bool condition, string message = "Argument must satisfy the specified condition.", string? parameterName = null)

Performs a general pre-condition requirement that fails when the specified condition is false.

Parameter Type Description
condition bool The condition to check.
message string The exception message to throw when condition is false.
parameterName string? The name of the invalid parameter.

Exceptions

Exception Condition
ArgumentException condition is false.

Require(bool, ref PreconditionInterpolatedStringHandler, string?)

public static void Require(
    bool condition,
    [InterpolatedStringHandlerArgument(nameof(condition))] ref PreconditionInterpolatedStringHandler message,
    string? parameterName = null)

Performs a general pre-condition requirement that fails when the specified condition is false. The compiler selects this overload when message is an interpolated string, and passes condition to the PreconditionInterpolatedStringHandler, so the message is only formatted when condition is false.

Parameter Type Description
condition bool The condition to check.
message ref PreconditionInterpolatedStringHandler The interpolated exception message to throw when condition is false, which is only formatted when condition is false.
parameterName string? The name of the invalid parameter.

Exceptions

Exception Condition
ArgumentException condition is false.
// The message is only built when no entry matches.
Require(found, $"Entry '{name}' not found in {typeof(T).Name}.", nameof(name));

RequireIsFailure(Result, string, string?)

public static Failure RequireIsFailure(
    Result result,
    string message = "Argument must be a Failure state.",
    [CallerArgumentExpression(nameof(result))] string? parameterName = null)

Requires that the specified Result is a Failure.

Parameter Type Description
result Result The current Result to check.
message string The exception message to throw when result is not a Failure.
parameterName string? The name of the invalid parameter. Captured automatically from the result argument expression when not supplied.

Returns — The result cast to Failure.

Exceptions

Exception Condition
ArgumentException result is not of type Failure.

RequireIsSuccess(Result, string, string?)

public static Success RequireIsSuccess(
    Result result,
    string message = "Argument must be a Success state.",
    [CallerArgumentExpression(nameof(result))] string? parameterName = null)

Requires that the specified Result is a Success.

Parameter Type Description
result Result The current Result to check.
message string The exception message to throw when result is not a Success.
parameterName string? The name of the invalid parameter. Captured automatically from the result argument expression when not supplied.

Returns — The result cast to Success.

Exceptions

Exception Condition
ArgumentException result is not of type Success.

RequireIsFailure<T>(Result<T>, string, string?)

public static Failure<T> RequireIsFailure<T>(
    Result<T> result,
    string message = "Argument must be a Failure state.",
    [CallerArgumentExpression(nameof(result))] string? parameterName = null)

Requires that the specified Result<T> is a Failure<T>.

Parameter Type Description
result Result<T> The current Result<T> to check.
message string The exception message to throw when result is not a Failure<T>.
parameterName string? The name of the invalid parameter. Captured automatically from the result argument expression when not supplied.
Type Parameter Description
T The underlying type of the Result<T> instance.

Returns — The result cast to Failure<T>.

Exceptions

Exception Condition
ArgumentException result is not of type Failure<T>.

RequireIsSuccess<T>(Result<T>, string, string?)

public static Success<T> RequireIsSuccess<T>(
    Result<T> result,
    string message = "Argument must be a Success state.",
    [CallerArgumentExpression(nameof(result))] string? parameterName = null)

Requires that the specified Result<T> is a Success<T>.

Parameter Type Description
result Result<T> The current Result<T> to check.
message string The exception message to throw when result is not a Success<T>.
parameterName string? The name of the invalid parameter. Captured automatically from the result argument expression when not supplied.
Type Parameter Description
T The underlying type of the Result<T> instance.

Returns — The result cast to Success<T>.

Exceptions

Exception Condition
ArgumentException result is not of type Success<T>.

RequireIsNone<T>(Optional<T>, string, string?)

public static None<T> RequireIsNone<T>(
    Optional<T> optional,
    string message = "Argument must be a None<T> value.",
    [CallerArgumentExpression(nameof(optional))] string? parameterName = null)
    where T : notnull

Requires that the specified Optional<T> is a None<T>.

Parameter Type Description
optional Optional<T> The current Optional<T> to check.
message string The exception message to throw when optional is not a None<T>.
parameterName string? The name of the invalid parameter. Captured automatically from the optional argument expression when not supplied.
Type Parameter Description
T The underlying type of the Optional<T> instance. Must be non-nullable.

Returns — The optional cast to None<T>.

Exceptions

Exception Condition
ArgumentException optional is not of type None<T>.

RequireIsSome<T>(Optional<T>, string, string?)

public static Some<T> RequireIsSome<T>(
    Optional<T> optional,
    string message = "Argument must be a Some<T> value.",
    [CallerArgumentExpression(nameof(optional))] string? parameterName = null)
    where T : notnull

Requires that the specified Optional<T> is a Some<T>.

Parameter Type Description
optional Optional<T> The current Optional<T> to check.
message string The exception message to throw when optional is not a Some<T>.
parameterName string? The name of the invalid parameter. Captured automatically from the optional argument expression when not supplied.
Type Parameter Description
T The underlying type of the Optional<T> instance. Must be non-nullable.

Returns — The optional cast to Some<T>.

Exceptions

Exception Condition
ArgumentException optional is not of type Some<T>.

RequireNotNullOrEmpty(string?, string, string?)

public static string RequireNotNullOrEmpty(
    [NotNull] string? value,
    string message = "Argument must not be null or empty.",
    [CallerArgumentExpression(nameof(value))] string? parameterName = null)

Requires that the specified string is neither null nor empty.

Parameter Type Description
value string? The string value to check.
message string The exception message to throw when value is null or empty.
parameterName string? The name of the invalid parameter. Captured automatically from the value argument expression when not supplied.

Returns — The non-null, non-empty value.

Exceptions

Exception Condition
ArgumentException value is null or an empty string.

RequireNotNullOrWhiteSpace(string?, string, string?)

public static string RequireNotNullOrWhiteSpace(
    [NotNull] string? value,
    string message = "Argument must not be null or whitespace.",
    [CallerArgumentExpression(nameof(value))] string? parameterName = null)

Requires that the specified string is neither null nor whitespace.

Parameter Type Description
value string? The string value to check.
message string The exception message to throw when value is null or whitespace.
parameterName string? The name of the invalid parameter. Captured automatically from the value argument expression when not supplied.

Returns — The non-null, non-whitespace value.

Exceptions

Exception Condition
ArgumentException value is null or consists only of whitespace.

RequireNotNull<T>(T?, string, string?)

public static T RequireNotNull<T>(
    [NotNull] T? value,
    string message = "Argument must not be null.",
    [CallerArgumentExpression(nameof(value))] string? parameterName = null)

Requires that the specified reference-type value is not null. This overload applies to reference types.

Parameter Type Description
value T? The nullable value to check.
message string The exception message to throw when value is null.
parameterName string? The name of the invalid parameter. Captured automatically from the value argument expression when not supplied.
Type Parameter Description
T The underlying type of the value.

Returns — The non-null value.

Exceptions

Exception Condition
ArgumentNullException value is null.

RequireNotNull<T>(T?, string, string?) (struct)

public static T RequireNotNull<T>(
    [NotNull] T? value,
    string message = "Argument must not be null.",
    [CallerArgumentExpression(nameof(value))] string? parameterName = null)
    where T : struct

Requires that the specified nullable value-type value is not null. This overload applies to value types via the where T : struct constraint, accepting Nullable<T>.

Parameter Type Description
value T? The nullable value to check.
message string The exception message to throw when value is null.
parameterName string? The name of the invalid parameter. Captured automatically from the value argument expression when not supplied.
Type Parameter Description
T The underlying value type. Must be a struct.

Returns — The non-null value.

Exceptions

Exception Condition
ArgumentNullException value is null.

RequireWithinRangeInclusive<T>(T, T, T, string, string?)

public static T RequireWithinRangeInclusive<T>(
    T value,
    T minimum,
    T maximum,
    string message = "Argument must be within range.",
    [CallerArgumentExpression(nameof(value))] string? parameterName = null)
    where T : IComparable<T>

Requires that the specified value falls within the inclusive minimum and maximum bounds.

Parameter Type Description
value T The value to check.
minimum T The inclusive minimum value to test.
maximum T The inclusive maximum value to test.
message string The exception message to throw when value falls outside the range.
parameterName string? The name of the invalid parameter. Captured automatically from the value argument expression when not supplied.
Type Parameter Description
T The underlying type of the value to check. Must implement IComparable<T>.

Returns — value, if it falls within the inclusive range.

Exceptions

Exception Condition
ArgumentOutOfRangeException value falls inclusively outside minimum and maximum.

RequireWithinRangeExclusive<T>(T, T, T, string, string?)

public static T RequireWithinRangeExclusive<T>(
    T value,
    T minimum,
    T maximum,
    string message = "Argument must be within range.",
    [CallerArgumentExpression(nameof(value))] string? parameterName = null)
    where T : IComparable<T>

Requires that the specified value falls within the exclusive minimum and maximum bounds.

Parameter Type Description
value T The value to check.
minimum T The exclusive minimum value to test.
maximum T The exclusive maximum value to test.
message string The exception message to throw when value falls outside the range.
parameterName string? The name of the invalid parameter. Captured automatically from the value argument expression when not supplied.
Type Parameter Description
T The underlying type of the value to check. Must implement IComparable<T>.

Returns — value, if it falls within the exclusive range.

Exceptions

Exception Condition
ArgumentOutOfRangeException value falls exclusively outside minimum and maximum.

RequireIsDefined<T>(T, string?)

public static T RequireIsDefined<T>(
    T value,
    [CallerArgumentExpression(nameof(value))] string? parameterName = null)
    where T : struct, Enum

Requires that the specified value is a defined member of the enumeration type T. When the value is undefined, the thrown exception message lists the valid member names.

Parameter Type Description
value T The enum value to check.
parameterName string? The name of the invalid parameter. Captured automatically from the value argument expression when not supplied.
Type Parameter Description
T The enumeration type. Must be a struct that is an Enum.

Returns — value, if it is defined by the enumeration type T.

Exceptions

Exception Condition
ArgumentOutOfRangeException value is not a defined member of the Enum type T.

See Also

ONIXLabs .NET Library


Clone this wiki locally