Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive Boolean size in C#

Tags:

c#

boolean

People also ask

What is the size of Boolean in C?

Boolean variables can either be True or False and are stored as 16-bit (2-byte) values. Boolean variables are displayed as either True or False. Like C, when other numeric data types are converted to Boolean values then a 0 becomes False and any other values become True.

Is a Boolean 1 bit or 1 byte?

It's a question many may ask when they discover that in C or C++ a Boolean variable or 'bool' for short, is simply an alias for a 4-byte unsigned integer (actually 1-byte oops). Shock horror! Any self-respecting novice in the field might ask “but we can fit eight booleans in just one byte!

What is the size of Boolean?

Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False.

Why is a Boolean 4 bytes?

Why does a System. Boolean take 4 bytes? It just stores one state, either true or false, which could be stored in less space than 4 bytes.


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!