Search code examples
c#arraysimmutabilityimmutable-collections

Looking for usable immutable bool array in C#


I have a class which has an bool array member. If I modify an element of this array, a new modified copy of the instance should be created. Sounds like a perfect opportunity for using an Immutable type. Googling around showed that Microsoft provides a new library Immutable Collections which works quite well for another use case. But not for the aforementioned bool array member.

The seemingly fitting type ImmutableArray has been removed for time being and the documentation didn't seem to contain an indexer as well. The potential replacement ImmutableList doesn't work with structs. I'm loathe to introduce another third party library, so I'm wondering what options I have and which I should choose.

I could create a class Bool to satisfy the reference type requirement. Or I could use BitArray, but trying to use like this fails with a compile error:

IReadOnlyList<BitArray> test = new IReadOnlyList<BitArray>(new BitArray());

So any ideas what I should do?


Solution

  • Note that this is perfectly valid:

    var ba = new BitArray(10);
    ba.SetAll(true);
    
    IImmutableList<bool> test = ba.Cast<bool>().ToImmutableList();
    

    Your problem is that the immutable item type is bool, not BitArray! And that BitArray is from the pre-generics era, so it doesn't support IEnumerable<bool>, ICollection<bool>, IList<bool>, so you can't use it directly (see the .Cast<bool>() to solve this)