BinaryFormatter , exact TYPE-SIZE buffer


I have this serializable class :

public class myClass

     public byte myByte { get; set; }
     public short myShort { get; set; }
     public int myInt { get; set; }

knowing that the type BYTE is 1 byte and the type SHORT is 2 bytes and the type INT is 4 bytes, i was waiting for a 7 bytes buffer but with the following code I got a buffer size of 232 byte:

myClass mc = new myClass { myByte = 0xff, myShort = 0x009c, myInt = 0x00000045 };
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, mc);
byte[] buffer = ms.ToArray();

I would like to send over IP the 'exact type-sized buffer' without hassling with a code like the follwing :

byte[] exactBuffer = new byte[sizeof(byte) + sizeof(short) + sizeof(int)];
exactBuffer[0] = mc.myByte;
byte[] bmyShort = BitConverter.GetBytes(mc.myShort);
System.Buffer.BlockCopy(bmyShort, 0, exactBuffer, sizeof(byte), bmyShort.Length);
byte[] bmyInt = BitConverter.GetBytes(mc.myInt);
System.Buffer.BlockCopy(bmyInt, 0, exactBuffer, sizeof(byte)+sizeof(short), bmyInt.Length);

and I need the class to be a class not a struct. Is there any way ?

asked on Stack Overflow May 9, 2011 by WaMe • edited May 10, 2011 by John Saunders

1 Answer


You could use interop and code like suggested int this post. But be aware that the language is allowed to use any memory layout it wishes, if you don't specify it, so you should use the StructLayout attribute.

Also, if your class contained any references to other classes, this wouldn't work.

In general, transferring data like this over network tends not to be the solution and you should use something like BinaryFormatter, XML or JSON.

answered on Stack Overflow May 9, 2011 by svick

User contributions licensed under CC BY-SA 3.0