Skip to content

[API Proposal]: Add constructor BitArray(IEnumerable<bool> values) #121737

Description

@pCYSl5EDgo

Background and motivation

I would like to propose adding a new constructor to System.Collections.BitArray that takes an IEnumerable<bool> as its parameter, similar to other collection types.
This would allow BitArray to be instantiated directly from an IEnumerable<bool>, improving usability and consistency with other collection classes.

API Proposal

namespace System.Collections;

public sealed class BitArray
{
+ public BitArray(System.Collections.Generic.IEnumerable<bool> values)
}

API Usage

IEnumerable<bool> enumerable = Enumerable.Range(0, 100).Where(static x => x % 31 == 0).Select(static x => (x & 1) == 0);
BitArray array = new(enumerable);
foreach (bool item in array.OfType<bool>())
{
    Console.WriteLine(item ? "event" : "odd");
}

Alternative Designs

If this constructor is not available, the following sample code would likely be the most optimal way to initialize a BitArray:

The code sample without `BitArray` with `IEnumerable` parameter.
BitArray array;
IEnumerable<bool> enumerable = // something;
if (Enumerable.TryGetNonEnumeratedCount(enumerable, out int count))
{
    array = new BitArray(count);
    Span<byte> destination = CollectionsMarshal.AsBytes(array);
    int index = -1;
    foreach (bool sourceItem in enumerable)
    {
        ++index;
        if (sourceItem)
        {
            destination[index >>> 3] |= (byte)(1 << (index & 7));
        }
    }
}
else
{
    List<bool> list = enumerable.ToList(); // x8 allocation
    array = new BitArray(list.Count);
    Span<byte> destination = CollectionsMarshal.AsBytes(array);
    ReadOnlySpan<bool> source = CollectionsMarshal.AsSpan(list);
    for (int index = 0; index < source.Length; index++)
    {
        if (source[index])
        {
            destination[index >>> 3] |= (byte)(1 << (index & 7));
        }
    }
}

With this constructor available, even if Enumerable.TryGetNonEnumeratedCount returns false and enumeration is required to determine the count, the temporary expansion buffer could be a bit-packed list instead of a List<bool>. This would reduce memory usage to one-eighth of the current requirement.

The above sample code is already sufficient for the constructors BitArray(IEnumerable<int>) and BitArray(IEnumerable<byte>), so adding dedicated constructors for these types would not be necessary.

the alternate API

namespace System.Collections;

public sealed class BitArray
{
+ public static BitArray Create<TSource>(TSource values) where TSource : System.Collections.Generic.IEnumerable<bool>
}

This alternative API would have the advantage of avoiding boxing allocations when the IEnumerable<bool> argument comes from a value-type collection. However, such cases are extremely rare—Unity’s NativeArray<bool> is probably the only notable example. Given this, I don’t think it’s necessary to optimize the API to that extent, and a straightforward constructor would be perfectly suitable.

Risks

No response

Activity

  1. added
    api-suggestion
    on Nov 18, 2025
  2. added
    untriaged
    on Nov 18, 2025
  3. dotnet-policy-service commented on Nov 18, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-collections
    See info in area-owners.md if you want to be subscribed.

  4. eiriktsarpalis commented on Nov 18, 2025

    @eiriktsarpalis
    Member

    This feels like it should be a ToBitArray(this IEnumerable<bool>) as opposed to a constructor or static factory. It doesn't feel like it would be a particularly impactful addition though, and it could easily be implemented as an extension method.

  5. pCYSl5EDgo commented on Nov 18, 2025

    @pCYSl5EDgo
    Author

    @eiriktsarpalis
    If it would be added as an extension method, should it be added to System.Linq.Enumerable?

  6. eiriktsarpalis commented on Nov 18, 2025

    @eiriktsarpalis
    Member

    Yes, although like I said I remain unconvinced this would be useful to the vast majority of LINQ users.

  7. pCYSl5EDgo commented on Nov 18, 2025

    @pCYSl5EDgo
    Author

    That’s fair — though I’d suggest the lack of usage might stem more from how inconvenient it’s been so far. If we make it easier and more discoverable, I believe usage patterns will naturally grow over time.
    After all, in C++, std::vector<bool> and std::array<bool, N> are bit-packed by default, which makes them an obvious and efficient choice in many contexts. That kind of default compactness has a strong influence on how developers approach bit-oriented problems — it’s not just about performance, but about discoverability and habit formation. Perhaps the relatively low usage in C# reflects that we haven’t yet offered a similarly natural path.

  8. eiriktsarpalis commented on Nov 18, 2025

    @eiriktsarpalis
    Member

    Maybe, although I would stress that BitArray is a specialized, performance oriented collection while LINQ is very much not that. A typical component using LINQ would pick List<bool> over BitArray and wouldn't stress about it.

  9. pCYSl5EDgo commented on Nov 18, 2025

    @pCYSl5EDgo
    Author

    You're right that when we talk about “specialized collections,” the examples that come to mind tend to be things like Sorted collection or Frozen collection(Neither of them is used in typical LINQ use cases). Though one is instantiated by a constructor while the other is instantiated by an extension method.
    I'll take a closer look at the design discussions from that time to better understand the reasoning.

  10. tannergooding commented on Nov 18, 2025

    @tannergooding
    Member

    This feels like it should be a ToBitArray(this IEnumerable) as opposed to a constructor or static factory. It doesn't feel like it would be a particularly impactful addition though, and it could easily be implemented as an extension method.

    Not so sure on this one...

    This seems more like the List<T> case where you have a constructor that takes IEnumerable<T> (and fits in with the other existing BitArray constructors). We do also happen to have ToList(...) but that is in part because of how prevalent List is, which I don't think we'd say for BitArray.

    Still not really sure its "needed" here, particularly since it is something a user could roll themselves since we have the CollectionsMarshal.AsSpan API for BitArray now. But if we were to expose it ourselves, I'd think a constructor would be fine/better

  11. tannergooding commented on Nov 18, 2025

    @tannergooding
    Member

    -- Noting that we also have .ctor(IEnumerable<T>) for other collection types like Queue, Stack, HashSet, Dictionary, etc. We don't have To*() LINQ APIs for most of these. So the constructor case is already the more general pattern with the LINQ case being the special one for key types.

  12. pCYSl5EDgo commented on Dec 12, 2025

    @pCYSl5EDgo
    Author

    The reason the FrozenDictionary/FrozenSet factories were implemented as extension methods is that the public types are abstract. Since the concrete frozen implementations are internal, providing public constructors was not an option, so extension methods were the natural design.

    BitArray, however, is a sealed concrete type. Given that BitArray already follows this constructor-based model for its existing overloads, an IEnumerable<bool> constructor seems more consistent with existing collection APIs than introducing a LINQ extension.

  13. added
    api-ready-for-review
    and removed
    api-suggestion
    on Aug 17, 2026
  14. added this to the Future milestone on Aug 17, 2026
  15. removed
    untriaged
    on Aug 17, 2026
  16. bartonjs commented on Sep 8, 2026

    @bartonjs
    Member

    Video

    • Since BitArray already also takes byte[] and int[], and we paralleled that in the ReadOnlySpan ctors, we should do all three here.
    namespace System.Collections;
    
    public sealed class BitArray
    {
        public BitArray(System.Collections.Generic.IEnumerable<bool> values);
        public BitArray(System.Collections.Generic.IEnumerable<byte> values);
        public BitArray(System.Collections.Generic.IEnumerable<int> values);
    }
  17. added
    api-approved
    and removed
    api-ready-for-review
    on Sep 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-System.Collections

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions