Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a generic (type-safe) BitArray in .NET?

Tags:

c#

.net

bitarray

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?)


Edit:

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?


Example:

foreach (bool bit in myBitArray)
{

}

Edit:

I just checked the enumerator of the BitArray class, but everything returns an object except .Current property:

public virtual object Current
like image 730
Joan Venge Avatar asked Nov 28 '22 19:11

Joan Venge


1 Answers

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);
}
like image 121
Henk Holterman Avatar answered Dec 06 '22 02:12

Henk Holterman