Skip to content

Add a ValidElements method to Requires #41

Description

@scottdorman

It would be nice to have a convenience method on Requires which easily allows validating a collection against a predicate. This method could look similar to:

[DebuggerStepThrough]
public static void ValidElements<T>([ValidatedNotNull] IEnumerable<T>? values, Predicate<T> predicate, string parameterName, string message)
{
    if (predicate is null)
    {
        throw new ArgumentNullException(nameof(predicate));
    }

    if (values is object)
    {
        foreach (T value in values)
        {
            if (!predicate(value))
            {
                throw new ArgumentException(message, parameterName);
            }
        }
    }
}

This could then be used like

public void SetFieldWidths(params int[] fieldWidths)
{
    Requires.NotNullOrEmpty(fieldWidths, nameof(fieldWidths));
    Requires.ValidElements(fieldWidths.SkipLast(1), fw => fw >= 0, "All width's except the last must be greater than 0", nameof(fieldWidths));
}

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions