Primitive Boolean size in C#

boolean, c#

Solution

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

Problem

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?

Original source

Related problems