I'm writing some classes that are going to be used to communicate with a C# TCP server, and I'm writing serialization/deserialization methods using BinaryWriter
and BinaryReader
. This is easy enough, but I've run into a situation where I have a class Class1 that contains an instance Class2 inside. Both classes implement an interface that defines methods byte[] ToBytes()
and void FromBytes(byte[] data)
. So I've got this code:
public class Class1
{
public int Action;
public Class2 Data;
public void FromBytes(byte[] data)
{
BinaryReader br = new BinaryReader(new MemoryStream(data));
Action= br.ReadInt32();
Data = new Class2();
Data.FromBytes(br.ReadBytes(___));
br.Close();
}
}
The problem is, what goes into the ReadBytes
call? I'm not sure of a way to do it other than to hard-code the size of any object that implements this interface, but is there something more elegant? I considered using reflection to calculate it at run-time (caching it for future calls), but this seems even uglier.
edit: I should point out that if the data is going to be variable-length, the binary representation includes the data lengths where necessary, and the deserializer would handle it.