I created a simple struct which consists of two value types.
public struct Identifier
{
public Guid ID { get; set; }
public Byte RequestType { get; set; }
}
Then I called Marshal.SizeOf() method on the custom struct Identifier using the following statements.
Identifier i = new Identifier();
Console.WriteLine(Marshal.SizeOf(i)); // output: 20
Console.WriteLine(Marshal.SizeOf(i.GetType())); // output: 20
Why does Marshal.SizeOf() not return 17?
The following instructions show that a Guid object is 16 bytes and a Byte object is 1 byte.
Guid g = Guid.NewGuid();
Console.WriteLine(Marshal.SizeOf(g)); // output: 16
Console.WriteLine(Marshal.SizeOf(g.GetType())); // output: 16
Byte t = 0;
Console.WriteLine(Marshal.SizeOf(t)); // output: 1
Console.WriteLine(Marshal.SizeOf(t.GetType())); // output: 1
By default the CLR is allowed to rearrange (which for simple structs it never does) and pad structs as it pleases. This is typically to keep it aligned to word boundaries when in memory.
If you don't like this behavior and want to change it, you can specify no packing as follows:
[StructLayout(LayoutKind.Sequential,Pack=1)]
Your Identifier struct is padded with 3 bytes when copied to unmanaged memory for alignment reasons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With