Hi i have a structure as follows
private struct MessageFormat
{
public byte[] Header; //start of message
public byte Fragmentation; //single packet or not
public byte Encryption; //encrypted message
public byte[] Authentication; //password
public byte[] Flag; //to locate end of auth
public byte[] Data; //info
public byte[] Trailer; //end of message
}
is there a handy way to convert the whole MessageFormat into a single byte array[] after i populate all the fields?
I’ve written a sample code which will do exactly what you asked. It combines Reflection and
Buffer.BlockCopybut it can be made MUCH more performant (i.e. boxingformatin advance, avoiding anonymous types — and their awkward, redundant initialization in the example — or even not using Reflection at all and hardcoding the serialization method). Note that the method I offer doesn’t use a buffer for the result but calculates the final length before allocating the array.