Skip to content

IEnumerable<T>.All() should return false for empty collections #80793

@dmombach

Description

@dmombach

Description

IEnumerable.All() returns true for empty collections; which can be misleading to developers.

Verifying all elements of a collection against a predicate should not return true if the collection is empty.
Returning true would tell developers that all of the collection elements are in conformity with the predicate; however, if there are no elements, returning true is misleading and can cause hard-to-find bugs.

Suggestion, changing the original extension method:

` public static bool All(this IEnumerable source, Func<TSource, bool> predicate)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}

        if (predicate == null)
        {
            ThrowHelper.ThrowArgumentNullException(ExceptionArgument.predicate);
        }

        if (!source.Any())
        {
            return false;
        }

        foreach (TSource element in source)
        {
            if (!predicate(element))
            {
                return false;
            }
        }

        return true;
    }`

Reproduction Steps

`
var list = new List();

var test = list.All(i => i.Year == 2000);

// variable 'test' will be true, but the collection is empty, so no elements match the predicate!
`

Expected behavior

IEnumerable.All() should return false for empty collections:

`
var list = new List();

var test = list.All(i => i.Year == 2000);

// variable 'test' should be false because the collection is empty, so no elements match the predicate!
`

Actual behavior

IEnumerable.All() returns true for empty collections:

`
var list = new List();

var test = list.All(i => i.Year == 2000);

// variable 'test' is true, but the collection is empty thus no elements match the predicate!
`

Regression?

No response

Known Workarounds

Verify if a collection is not empty before checking its elements with the IEnumerable.All() extension method:

`
var list = new List();

var test = list.Any() && list.All(i => i.Year == 2000);

// variable 'test' will be false
`

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions