There is a code using the StructLayout attribute with generic as below.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Packet<H, Body1, Body2> : IOutlinePacket
where H : new()
where Body1 : IDeviceBody, new()
where Body2 : INetworkBody, new()
{
H Header = new Header();
Body1 DeviceBody = new Body1();
Body2 NetworkBody = new Body2();
}
If the class is not generic the sequence of H, Body1, Body2 will be guaranteed and will be allocated by a 1byte step. But I don't know how about the generic type case.
Of course, I know the generic type is not supported the marshal function but I want to know how about StructLayout case.
I tried to a few test to check this and according to a tests, it seems to be work but I don't know whether it is a coincidence or it is always work.
I'm sorry for my terrible English and Thank you for reading.
This will work as expected. If you add
StructLayoutwhich specifies a packing to a generic class, it will add a.packdirective to the IL generated.For example, given this class:
The IL output for this is something like this:
Note the
.pack 1, which specifies the packing.You can verify that this packing does in fact work by writing some
unsafecode along these lines:The output of this when using
Pack = 1is1.If you change the packing to
Pack = 4, the output is4.And if you change the packing to
Pack = 8, the output is8.This demonstrates that the packing in memory is performed, even without using marshalling.
I'm not totally sure what you mean by this, but it could be that "discriminated unions" might be of use to you in the future - but it doesn't look like they will be implemented any time soon, so possibly it will be years before they are available (if ever).
Also note that this only works with blittable types!
See here for the documentation