Looking for a useful immutable bool array in C #

I have a class that has a bool array element. If I modify an element of this array, a new modified copy of the instance needs to be created. Sounds like a great opportunity to use an immutable type. A Google search revealed that Microsoft is providing a new Immutable Collections library that is great for another use case. But not for the above bool array element.

It looks like the appropriate type ImmutableArray has been removed for the time being and the documentation doesn't seem to contain a pointer. Potential replacement ImmutableList doesn't work with structs. I don't want to introduce another third party library, so I'm wondering what options I have and which should I choose.

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

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

      

So, any ideas what I should be doing?

+3


source to share


1 answer


Note that this is perfectly true:

var ba = new BitArray(10);
ba.SetAll(true);

IImmutableList<bool> test = ba.Cast<bool>().ToImmutableList();

      



Your problem is that the element type is immutable bool

, not BitArray

! And it BitArray

belongs to the era to generation, so it does not support IEnumerable<bool>

, ICollection<bool>

, IList<bool>

therefore you can not use it directly (see. .Cast<bool>()

To solve the problem)

+2


source







All Articles