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?