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
No, there isn’t.I’m not even sure what part of a BitArray would be generic if there were one.
It wouldn’t be hard to create an extension method to take the
BitArrayand return abool[]orList<bool>using aforloop on theBitArray. Theforloop would not involve boxing since you would be using theBitArray‘s indexer, and thebool[]List<bool>could be enumerated without boxing as well.Example extension method:
What I found from a quick benchmark (curiosity overcame me) was that
foreach (bool b in myBitArray.ToList())took 75% to 85% of the time thatforeach (bool b in myBitArray). That creates the list each time. Creating the list once and iterating over it many times took 20% to 25% of the time thatforeach (bool b in myBitArray)took. You could only take advantage of that if you need to iterate over theboolvalues multiple times and know that they won’t have changed from the time you calledmyBitArray.ToList().foreach (bool b in Enumerable.Cast<bool(myBitArray))took 150% of the time thatforeach (bool b in myBitArray)took.Yet another edit: I’d say that since it is a game, it probably does make sense for you to do whatever it takes to have a very lean iteration with no boxing/unboxing, even if that means writing your own
BitArray. You could save time and use Reflector tocopy most ofstudyBitArray‘s code since the class is sealed (can’t inherit and add functionality), just in case there are bit-twiddling optimizations to learn from.Edit: Struck the suggestion to copy code out of Reflector. Some things, like iterators and closures, yield weird generated code that you don’t want to copy directly anyway.