Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sizeof(bool) == sizeof(byte) in C#? [duplicate]

Possible Duplicate:
What is the binary representation of a boolean value in c#

According to the MSDN documentation, the sizeof keyword is "used to obtain the size in bytes for an unmanaged type" and primitives are considered unmanaged types. If I check the sizeof(bool), the result is 1.

It seems to me that using a Boolean value should only require a bit of memory. Am I mistaken? Does using a Boolean value actually requires a full byte of memory? Why?

like image 845
smartcaveman Avatar asked Sep 02 '12 09:09

smartcaveman


2 Answers

It uses a whole byte of memory for performance reasons.

If it only used a single bit, what do you do with the other 7 bits? Few variables are booleans, and other variables may not require a single bit. So it would only be useful for other booleans.

For example, 4-byte integers. Also, many larger types need to start at appropriate byte boundaries for performance reasons. For example, a CPU may not allow you to easily reference a 4-byte address starting from any address (ie. the address may need to be divisible by 4).

If it used a single bit of memory, meaning the other 7-bits could be used for other booleans, trying to use this boolean would be more complicated. Because it is not directly addressable, you would need to get the byte, and then extract the bit, before testing if it is 1 or 0. That means more instructions - hence slower performance.

If you have many booleans, and you want them to only use a single bit of memory EACH, you should use a BitArray. These are containers for single bits. They act like arrays of booleans.

like image 54
ronalchn Avatar answered Oct 01 '22 23:10

ronalchn


A byte is the smallest amount of addressable memory. The .NET team have chosen to use a byte to store a bool to simplify the implementation.

If you want to store a large number of bits more compactly you can look at BitArray.

like image 35
Mark Byers Avatar answered Oct 01 '22 23:10

Mark Byers