In C/C++, you're guaranteed that fields are stored in memory in the
order they're declared. For example, (assuming x86) in
class foo {
int x;
double y;
int z;
};
the memory layout will be x, then y, then z. But as you may be aware,
there may be alignment issues. Ignoring vtable issues and the like, x is
at offset 0, but y probably isn't at offset 4, but at offset 8 (and z at
offset 16). Some CPU architectures perform better if data is aligned on
"natural boundaries" (and some will actually abort if the data isn't
aligned). So doubles are preferentially stored at addresses that are a
multiple of 8, and there would be 4 bytes of padding (uninitialized,
ignored data) between x and y. You must (again, talking just C/C++) use
some extra-language feature (usually #pragma) to adjust (e.g. eliminate)
these pad bytes).
C# addresses this issue by ***not*** guaranteeing that data is stored in
the order you declare. In the above case, it might store data in memory
in the order y, x, z. Or even y, z, x. Or x, z, y (or z, x, y). All of
which satisfy alignment rules, and save 4 bytes of padding per instance.
To get around this, prefix your class with
[StructLayout(LayoutKind.Sequential)]
class foo ...
You'll also need a
using System.Runtime.InteropServices;
for the StructLayoutAttribute et al.
HTH
P.S. Side note: Without StructLayout, the alignments are *not*
determined at compile time, since the compiler doesn't know if this will
be run on a 32-bit architecture, 64-bit, different CPU families (x86,
PowerPC, etc), all of which may have different alignment rules.