What's the size of this C# struct?

Take a look at @Hans Passant's answer here for interesting background on this issue, esp. with regard to the limitations of Marshal.Sizeof.


Marshal.SizeOf()

http://msdn.microsoft.com/en-us/library/y3ybkfb3.aspx


The CLR is free to lay out types in memory as it sees fit. So it's not possible to directly give "the" size.

However, for structures it's possible to restrict the freedom of the CLR using the StructLayout Attribute:

  • Auto: The runtime automatically chooses an appropriate layout.
  • Sequential: The members of the object are laid out sequentially and are aligned according to the StructLayoutAttribute.Pack value.
  • Explicit: The precise position of each member is explicitly controlled.

The C# compiler automatically applies the Sequential layout kind to any struct. The Pack value defaults to 4 or 8 on x86 or x64 machines respectively. So the size of your struct is 8+4=12 (both x86 and x64).


Unrelated from how a type is laid out in memory, it's also possible to marshal a type in .NET using the Marshal Class. The marshaller applies several transformations when marshalling a type, so the result is not always the same as the way the CLR laid out the type. (For example, a bool takes 1 byte in memory plus alignment, while the marshaller marshals a bool to 4 bytes.)

Tags:

C#

Struct

Sizeof