Wednesday, September 10, 2014

Serialization behind the scene

In the post I am going to explain about the Binary Serialization internals.


With the Binary Serialization we can serialize any fields (Private, protected or public) which are not marked as NonSerializableAttribute.

FCL providers Formatter services and Formatters like BinaryFormatters to achieve serialization.
FormatterServices class provides some static methods to achieve Serialization and De-Serialization behind the scene , which are intern called by the Serialize and de-serialize methods of BinaryFormatter.

Let us look at the following Steps how Serialization and De-Serialization works using FormatterServices static methods.

Serialization:
·         public static MemberInfo[] GetSerializableMembers(
        Type type
        )
This method uses the reflection to get all the (private and public) instance fields and returns MemberInfo array.
·         The object being serialized and MemberInfo array passed to static method GetObjectData(Object obj, MemberInfo[] members). This methods returns array of objects where each element identifies the value of the field in the object being serialized.
·         Finally, the formatter then enumerates over the elements in the two arrays, writing each member's name and value to the byte stream.

De-Serialization:

·         public static Type GetTypeFromAssembly(
        Assembly assem,
        string name)
This method returns System.Type object indicating the type of object being De-Serialized

·         public static Object GetUninitializedObject(
        Type type)
This method allocates memory for the new object without calling constructor and all the object's bytes are initialized to null or 0.

·         The formatter now construct an object and initializes a MemberInfo array by calling GetSerializableMembers() method; This method returns set of the fields(Private and Protected also) that were serialized and that need to de-serialized.
·         The formatter now creates and initializes an object array from the data contained from the stream.
·         The reference to newly created object, MemberInfo array and object array data will be passed to PopulateObjectMembers (object obj, MemberInfo[] membrs, object[] data).
This method enumerates over the arrays, initializing each field to its corresponding value. At this point the object is completely De-serialized.

The above explanation is implemented in the below example.
Got help from:

 Special thanks to Jeffery Ritcher and MSDN for providing required internal details.

if any mistakes found in the blog, guide me correct direction