I’m writing binary serialiser/deserialser to convert a number of object types to/from a byte stream. The objects represent API commands and their associated responses for a device connected by Bluetooth or USB. I’m using the BinaryWriter & BinaryReader to write/read to/from the stream.
The serialiser is easy. The properites to be serialised are tagged with an attribute that specifies the order in which they are to be written to the byte stream. I iterate through the properties using reflection and overload resolution handles picking the correct Write(...) method of the BinaryWriter.
The deserialiser is not quite so simple. Again I can iterate through the properites in the particular response class that I’m expecting to determine the types that need to be read from the stream. The tricky bit is picking the correct method to call on the BinaryReader to read the value I need. I’ve thought of two approaches.
- A big switch statement that calls the correct
ReadXXXX()method based on the type to be read. - Use the name of the type I need to build the name of the method I need in a string, and then invoke the method using relection.
Is there a simpler way I’m not thinking of? It’s just a shame you can’t do overload resolution based on the return type you want.
I’ve used option 1 (big switch statement) in a binary deserializer. A cleaner method could be something like:
Another option is to let the command classes themselves do the serialization:
Then in your commands:
And generic serialization methods:
But this way you might end up duplicating some code. (On the other hand, derived classes can call their parent class versions of Serialize/Deserialize if that makes sense in your scenario, and that works nicely.)