Skip to content

[API Proposal]: Add IsEmpty property to collections and arrays. #79769

Open
@aKzenT

Description

@aKzenT

Background and motivation

See discussion in #75933 .

For performance reason using LINQ ".Any()" to check if a collection is empty is discouraged in favour of checking if Length and Count is greater than zero. However arguably using "Any()" expresses the intent more clearer and there could even be collection implementations where computing Count is more expensive than just checking if the collection is empty or not.

Adding an IsEmpty property would not only solve that issue but also align with other APIs that have an IsEmpty property like Span.

API Proposal

Since there are probably millions of existing implementations of collection types, using a default implementation that checks the Count might be the best option.

namespace System.Collections.Generic;

public interface ICollection<T>
{
    bool IsEmpty => Count == 0; 
}

API Usage

// Fancy the value
var c = new List<int>();

if(c.IsEmpty)
{

}

Alternative Designs

Improve performance of using Any() might solve part of the problem.

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.CollectionsblockedIssue/PR is blocked on something - see comments

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions