Today’s topic is Binary serialization, if you wish to read more about serialization or other types of serialization please visit this link:

Binary serialization is type of serialization where type fidelity and reference integrity are preserved, meaning assembly information, private and public fields are being preserved as well as theirs memory locations. You would normally use binary serialization to preserve application state, store it to a backing store (storage medium) and use it later to run application on same computer or maybe multiple other computers.

Hearth of binary serialization is BinaryFormatter class and its Serialize and Deserialize methods. Serialize and Deserialize  methods take two parameters stream and object graph and serialize or deserialize object accordingly. Result of serialization are unreadable to human eye but you can read some information:

Binary Formatter

BinaryFormatter serialization result

As you can see type and field information are preserved.

If you wish serialized data in more readable way you can use SoapFormatter. Note that SoapFormatter is obsolete so use it only for debugging and testing purposes.

SoapFormatter

SoapFormatter serialization result

To mark a type serializable use Serializable attribute to decorate type. Serializable attribute is not inherited so if you wish to serialize both base and derived class decorate both of them with serializable attribute. Other approach would be to implement ISerializable interface.

If you wish not to serialize filed add NonSerialized attribute.

You can serialize null types, but you can not serialize or deserialize null streams.

Properties are not serialized but their private fields are. Do not serialize auto implemented properties because you cannot guarantee that theirs private fields will have the same name on the other machines as they do on yours.

If we wish more control during Serialization/Deserialization processes we can use attributes from System.Runtime.Serialization and apply them to the methods.
Attributes we can use for methods during serialization:
OnSerializingAttribute – use this attribute to prepare data before deserializing . For example encrypt password field or change distance from miles to kilometers.
OnSerializedAttribute – restores type to a status it was before applying OnSerializingAttribute.

Attributes we can use for methods during serialization:
OnDeserializingAttribute – because serialization cannot use constructor, use this attribute for method that will simulate constructor, and maybe set fields to default values.
OnDeserializedAttribute – use this attribute to manually set value of the fields just after serialization process has finished.

 

Example for Binary serialization.

We will try to serialize data from Employee class:

 

 

Download link for entire solution is here.