C # structure size

I am new to C #.
I am trying to understand why the size of the structure is growing.
I.e:

struct Test
{
    float x;
    int y;
    char z;
}

the size of the test structure is actually 10 bytes (float = 4, int = 4, char = 2).
But when I tried to get sizeof struct using the method Marshal.SizeOf(..), I got 12.
In C ++, I did pragma pack(1)to prevent this, but how can I do this in C #?

Another question:
When I tried to convert the Test array to a byte array, if struct is not [Serialize], I got a 12 byte array of bytes as excluded (or not), but if struct [Serialize], I got a 170 byte array of bytes, why did this happen?
Thank you :)

+4
1

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TestStruct
{
    float x;
    int y;
    char z;
}

Marshal.SizeOf() == 9, Marshal.SizeOf(typeof(char)) == 1 .

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]

Marshal.SizeOf() == 10

+9

All Articles