5

I got a struct with the following fields

public struct Person
    {
        public int Age;
        public short Id;
        public byte Marks;
    }

When I initialise it and check the memory size, I get size as 8.

Person instance = new Person {Age = 10, Id = 1,Marks = 75};
Console.WriteLine(Marshal.SizeOf(instance));

However, when I change the order as below and execute it, I get the size as 12.

public struct Person
    {
        public byte Marks;//1 byte
        public int Age;//4
        public short Id;//2
    }

Ideally, it should be 7 bytes. However, from this link msdn I can understand that overhead allocation do happens. However, why is it not consistent? Why the order of properties inside a struct determines the size of its instance?

Hunter
  • 2,370
  • 2
  • 20
  • 24

1 Answers1

3

It is perhaps because of data alignment a.k.a. data structure padding.

E.g. on many 32-bit systems int should be at a memory offset which is some multiple of 4.

From http://en.wikipedia.org/wiki/Data_structure_alignment:

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

Perhaps in we have something like this:

public struct Person
{
    public int Age;     // 4 bytes
    public short Id;    // 2 bytes
    public byte Marks;  // 1 byte + 1 byte for padding
}

public struct Person
{
    public byte Marks; // 1 byte + 3 bytes for padding
    public int Age;    // 4 bytes
    public short Id;   // 2 bytes + 2 bytes for padding
}
AlexD
  • 32,156
  • 3
  • 71
  • 65
  • Thanks Alex. It means memory is allocated by the run time based on the word size of the processor. It adds additional padding bytes in this case so that int can be consumed. – Hunter Aug 07 '14 at 20:51
  • @Hunter Basically, `Person` does not have a predefined size, so `sizeof(Person)` cannot be used. See http://msdn.microsoft.com/en-us/library/kh2sh4dh.aspx. – AlexD Aug 07 '14 at 21:00
  • 1
    @Hunter See also http://stackoverflow.com/a/8048571. – AlexD Aug 07 '14 at 21:08