Like small data types packed in C #

I do not want to improve performance or memory usage, this question was simply caused by curiosity.

Main question Given the following class, does the C # compiler (Mono + .NET) pack two variables shortin 4 bytes or will they consume 8 bytes (with alignment)?

public class SomeClass {
    short a;
    short b;
}

Secondary question If the answer to the above question was not 4 bytes, can the following alternative offer any advantages (where it is SomeClassused in very large quantities):

// Warning, my bit math might not be entirely accurate!
public class SomeClass {
    private int _ab;

    public short a {
        get { return _ab & 0x00ff; }
        set { _ab |= value & 0x00ff;
    }
    public short b {
        get { return _ab >> 8; }
        set { _ab |= value << 8; }
    }
}
+5
source share
3 answers

, . [StructLayout], - .

, , struct class. . syncblk, TypeHandle .., ( 64- - 8 ), "" . . " CLR " .

, , , 8 ( ). couse , , , , 64- .

+5

, @David_M, [StructLayout], Pack, . [FieldOffset], ( , .NET).

+6

, , .

And yes, in the case of many objects that save space. What you are looking for is LayoutKind (StructLayout attribute). It allows you to collect items as you wish. For example, with Sequential, he will be sure that he is packed tightly.

[StructLayout(LayoutKind.Sequential)]
public class SomeClass {
    short a;
    short b;
}

For More Information MSDN-Structlayout

+2
source

All Articles