tags:

views:

112

answers:

2

How are boolean variables in C# stored in memory? That is, are they stored as a byte and the other 7 bits are wasted, or, in the case of arrays, are they grouped into 1-byte blocks of booleans?

This answers the same question regarding Java (http://stackoverflow.com/questions/1907318/java-boolean-primitive-type-size). Are Java and C# the same in this regard?

+1  A: 

In C# they are stored as 1 byte in an array or a field but interestingly they are 4 bytes when they are local variables. I believe the 1-byteness of bool is defines somewhere in the .NET docs unlike Java. I suppose the reason for the 4 bytes for local variables are to avoid masking the bits when readng 32bits in a register. Still the sizeof operator shows 1 byte because this is the only relevant size and everything else is implementation detail.

Stilgar
+3  A: 

In C#, certainly the bits aren't packed by default, so multiple bool fields will each take 1 byte. You can use BitVector32, BitArray, or simply bitwise arithmetic to reduce this overhead. As variables I seem to recall they take 4 bytes (essentially handled as int = Int32).

For example, the following sets i to 4:

struct Foo
{
    public bool A, B, C, D;
}
static unsafe void Main()
{
    int i = sizeof(Foo);
}
Marc Gravell
Note that trying to optimize this stuff is most likely premature. Unless you primarily operate on huge amounts of boolean data, they won't be the cause of any memory problems.
Anon.