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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With