Is there a generic BitArray in .NET? I only found the non-generic one.
Can there be a generic BitArray? (i.e. would it be reasonable?)
Maybe I should have said type-safe not generic.
Basically when you enumerate the type as object, should it not be int or bool? Or one of them provided in another member enumerator?
foreach (bool bit in myBitArray)
{
}
I just checked the enumerator of the BitArray class, but everything returns an object except .Current property:
public virtual object Current
                BitArray is a specialized collection class from the NET 1.x era. It is quite type-safe as long as you use ba.Set(int, bool) and the indexer property.
What is 'not typesafe' is the enumeration, BitArray implements IEnumerable but not IEnumerable< bool>.  So Joan is right, using foreach() involves casting from object to bool. 
But is that a real problem? The elements in a BitArray are booleans, and only meaningful when combined with their position. Note that BitArray does not have an Add() method, just a Set(i, true).
So the simple answer is: don't use foreach(), or anything else based on IEnumerable. It only produces a stream of true/false values that can hardly be useful.
In the following snippet the BitArray is perfectly type-safe and efficient:
BitArray isEven = ...;
for(int i = 0; i < isEven.Count; i++) 
{
   isEven.Set(i, i % 2 == 0);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With