views:

168

answers:

2
+1  Q: 

Byte serialization

I recently had a discussion with a colleague about serialization of byte data over a network. He used the BinaryFormatter class to "unparse" the byte data I was sending to him. This did not work and he obviously had exceptional... exceptions. Binaryformatter could not "unparse" the data correctly since my data was simply a byte array.

His motivation for BinaryFormatter was platform independence. I am not persuaded of such a stance. When we both used BinaryReader or BinaryWriter, things worked well in code land.

What is the use therefore of BinaryFormatter and should I look at using it in each scenario wherever I need to send bytes over the wire?

+1  A: 

Definitely, if you have your data as byte[], BinaryFormatter is not a wise thing to use. You just write the data out to the wire. However, if you have a set of objects and want to serialize them to a stream, BinaryFormatter is much easier to use than manually writing each field of each type by hand. The purpose of BinaryFormatter or any serializer/deserializer scheme in general is to provide a way to persist an object graph (possibly complex) as a sequence of bytes.

Mehrdad Afshari
+2  A: 

It sounds to me like you might want to look at something like "protocol buffers", which (unlike BinaryFormatter) is a high-performance, low-bandwidth, portable/cross-platform, version-tolerant binary serialization format (wow, that's a mouthful).

Fortunately, there are versions in .NET, such as protobuf-net.

(disclosure: I'm the author, but it is free; I'm not trying to sell you anything - just save you a lot of time and pain)

BinaryFormatter is very... brittle; it is .NET specific and has relatively poor version tolerance. The only time I use it is behind the scenes for communicating between AppDomains on the same machine. Otherwise, I'd look at contract-based serializers, such as XmlSerializer, DataContractSerializer, or protobuf-net.

Marc Gravell