Skip to content

[API Proposal]: ArgumentException.ThrowIfNullOrEmpty for collections and spans #115931

Closed as duplicate of#86830
@BarionLP

Description

@BarionLP

Background and motivation

throwing if a collection or span is empty

API Proposal

namespace System;

public class ArgumentException : SystemException
{
        public static void ThrowIfNullOrEmpty<T>([NotNull] T? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null) where T : System.Collections.ICollection
        {
            ArgumentNullException.ThrowIfNull(argument, paramName);
            if (argument.Count == 0)
            {
                throw new ArgumentException("The value cannot be an empty collection.", paramName);
            }
        }
        public static void ThrowIfEmpty<T>(ReadOnlySpan<T> argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null)
        {
            if (argument.IsEmpty)
            {
                throw new ArgumentException("The value cannot be an empty span.", paramName);
            }
        }
}

API Usage

List<string> values = [];
ArgumentException.ThrowIfNullOrEmpty(values);

Alternative Designs

could use static extension members to add this feature without changing ArgumentException

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions