This is how any binary
serialization works: before any piece of data, you write some descriptor of this data. In particular, you have to write some word which uniquely denotes the data type of next record. It can be anything, but it should definitively identify what's written next. Of course, the reading and writing part of your code should use the same definitions. It resembles some
transport protocol. Before each string, it's lengths should be written. Before the collection of object, the length of this collection should be written. And so on…
Now, it will only be a fully-fledged serialization, if you make it
type-agnostic. This is possible to achieve through reflection, and it's not trivial at all. You can probably understand it yourself if you understand how serialization works. Please see:
http://en.wikipedia.org/wiki/Serialization[
^],
https://msdn.microsoft.com/en-us/library/7ay27kt9%28v=vs.110%29.aspx[
^],
https://msdn.microsoft.com/en-us/library/ms733127%28v=vs.110%29.aspx[
^].
No, MSDN won't give you explanation on the internals, but if you want to develop such thing, you should be able to imagine it and design all the functionality. Or… perhaps you can use available serializer:
https://msdn.microsoft.com/en-us/library/72hyey7b%28v=vs.110%29.aspx[
^],
https://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter%28v=vs.110%29.aspx[
^].
Unfortunately, this serializer does not use data contract.
Now, the final and perhaps the hardest step: as reflection is slow, there is a way to accelerate it, at least not to perform all reflection work over and over on the same
data model. This is achieved by
System.Serialization.Emit
, which emits the serialization code on the fly. Such code requires fine understanding of CIL and is quite hard to debug. Care to try? :-)
See also:
https://en.wikipedia.org/wiki/Common_Intermediate_Language[
^],
https://msdn.microsoft.com/en-us/library/system.reflection.emit%28v=vs.110%29.aspx[
^],
http://www.drdobbs.com/generating-code-at-run-time-with-reflect/184416570[
^],
Dynamic Type Using Reflection.Emit[
^].
—SA