Primitive Boolean size in C#

Viewed 26017

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 (Why is Java's boolean primitive size not defined?). Are Java and C# the same in this regard?

2 Answers

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);
}

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.

Related