.NET has some special requirements for objects being serialized
The formatter is special class which formats the serialized data
Implements the IFormatter interface
A stream is used to store the serialized objects
Inheritor of System.IO.Stream
Objects can be serialized to MemoryStream , FileStream , NetworkStream , etc.
The serialization process relies on the formatter
The formatter iterates all object’s members recursively, using reflection
The scope modifiers do not matter
All elements are serialized (including private)
Static elements are not serialized
Formatters contains logic for formatting objects being serialized
CLR iterates the metadata for the members and extracts their values by reflection
These values are passed to the formatters
Standard formatters defined in the namespace System.Runtime.Serialization :
Developers can define their own user-defined formatters
Inherit the Formatter class
Which implements IFormatter
Deep copy is the operation that clones an object along with all its properties recursively
Deep copy == cloning of the entire object graph
Can be done using serialization
Sometimes we need to perform some things after an object have been deserialized
E.g. fill some transient fields with their default values
Just implement IDeserializationCallback and its method OnDeserialization()
CLR executes this method after the deserialization of the object is completed
What is XML Serialization?
Storing the public fields of an object in XML format in order to save or transport them
Supported by the .NETXML API
Can serialize all types of objects
Cannot handle cyclic graphs of objects
User defined classes must have parameterless constructor
The reverse process
Define classes Country and Town , which contains information about towns and countries. Consider that one country has many towns. Implement binary and XML serializations and deserializations for these classes.
Write a class called Graph , which describes directed graph, represented as list of neighbors for each vertex. Write a class Node , which describes a graph’s vertex. The class Node should contain data part (text field) and list of descendent nodes. Implement functionality to serialize and deserialize the instances of the class Graph .
Explain why BinaryFormatter can serialize cyclic graph of objects, and XML serialization can not. Hint: use the Graph class written in exercises, make it cyclic and serialize it in the both ways and compare the output XML files.