Using Marshal.SizeOf() method on a custom struct containing only value types

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.


CLR is not allowed to rearrange or pad structures. C#, Visual Basic, and C++ compilers apply the Sequential layout to structures by default. Even .NET 1.1 from 2003 (the oldest version with online documentation still available) did that, here’s a link for that old documentation.

The actual reason why the compiler pads your structure with 3 bytes at the end is C compatibility. For unmanaged interoperability reason, unless one messes with [StructLayout] attribute, C# uses structure packing rules copy-pasted from C programming language.

GUID structure has a first field of type int. And that’s the only reason why the compiler makes the size of your structure a multiple of 4 bytes.