Here's my code:
struct abc
{
short a;
byte b;
int c;
}
When I use:
Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(typeof(abc)));
It shows: 8
whereas it should show: 7
because in my machine: byte: 1
, short:2
, int:4
bytes respectively.
Why is it happening?
If it is happening due to padding, how to disable the padding while reading the size of the structure? Because i need the exact size of the structure in bytes. It's important.
It's showing 8
because of structure member alignment rules.
If you want to set your struct
as unaligned, you need to use StructLayout
with the Pack = 1
attribute like so:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct abc
{
short a;
byte b;
int c;
}
This should output 7
.
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