views:

293

answers:

3

In .net, does a bool[] use one bit or one byte per array item? ie, does it automatically pack the bool values? I know a single bool uses 1 byte, but maybe the CLR has a special case for bool[]...

+4  A: 

One byte per value. I'm trying to find where this is actually specified (if indeed it is) but it's true for the current .NET CLR.

EDIT: This is sort of confirmed by printing sizeof(bool) which prints 1 - although the sizeof operator in C# doesn't end up calling the sizeof IL instruction...

Jon Skeet
What's the size of a bool in other languages (Java/C/C++)?
Chris S
In Java a boolean is 1 byte as well (in an array).
Jon Skeet
In C/C++ it's also 1 byte size
Kamarey
The size of bool in C++ isn't specified. It is only guaranteed that it should be at least the size of char (at least 8 bits), and at most equal to the size of long. I think really old versions of VC++ and g++ implemented it as an enum typedef, which would make it as big as int. In newer versions of VC++, it is a built-in type of size 1 byte; it's probably the same for newer versions of g++ as well.
Firas Assaad
+7  A: 

What you want is a BitArray. bool[] gets no special treatment by the CLR.

Martinho Fernandes
very cool. had no idea this existed.
Dave Markle
+6  A: 

Concerning size, it stores an array of bools as an array of bytes, no special case there.

You might want to check the BitArray class if you want to pack data.

kek444