Primitive Boolean size in C#

前端 未结 2 1471
傲寒
傲寒 2020-12-05 17:16

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

相关标签:
2条回答
  • 2020-12-05 17:36

    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.

    0 讨论(0)
  • 2020-12-05 17:52

    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);
    }
    
    0 讨论(0)
提交回复
热议问题