Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the size of this C# struct?

Tags:

c#

struct

sizeof

Is it 12 bytes or 16 bytes when stored in a List<DataPoint>?

public struct DataPoint
{
    DateTime time_utc;
    float value;
}

Is there any sizeof function in C#?

like image 353
Meh Avatar asked Sep 27 '10 14:09

Meh


4 Answers

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

like image 86
Steve Townsend Avatar answered Nov 03 '22 10:11

Steve Townsend


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.)

like image 26
dtb Avatar answered Nov 03 '22 12:11

dtb


Marshal.SizeOf()

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

like image 7
Lou Franco Avatar answered Nov 03 '22 11:11

Lou Franco


It will be 12 bytes (4 for float, 8 for DateTime); Marshal.SizeOf will return 16 because the default packing is 8 bytes aligned. This is a good article on structs and packing. It gives a full description of whats actually happening.

like image 4
SwDevMan81 Avatar answered Nov 03 '22 11:11

SwDevMan81