Saturday, April 3, 2010

Serialization, basic concepts

Serialization is the process wich allows to take a "photo" of an object, and rebuild that object later from this "photo".
The BinaryFormatter class allows to store this photo in a FileStream, and to retrieve the original object again from the file.  If you wish one custom class to be serializable, you must adorn it with the Serializable attribute.  By default, the Serializable attibute indicates that every member of your class (either private members) must be serialized.
If you don't need a member serialized you must adorn it with the NonSerialized attribute.  If that member is calculated, it doesn't be recalculated on deserialization unless you specify that action implementing the IDeserializationCallback interface in your serializable class.  This class have the OnDeserialization method, wich must be implemented in order to specify the actions that will be performed after your class has been deserialized.
Compatibility problems may raise when you serialize different versions of the same class.  If you try to deserialize a previous version of a class wich lacks a recent added member, an exception will be thrown.  For avoid this you can use the OptionalField attribute on the new member.  Acting on this way the recently added member will be initialized to null or default instead of throwing the exception.
Besides the BinaryFormatter, wich is the most efficient way to perform serialization when the serialization object will be consumed only by .Net applications, we have the SoapFormatter, wich is XML based and more appropiate when your object will be used by a SOAP Web service, although the result is a more heavy serialized object.
Unlike the BinaryFormatter, wich behaviour rarely must be adapted, you must to specify the desired functionality of the SoapFormater through the following attributes:
  • SoapAttribute:  The member will be serialized as an XML attribute.
  • SoapElement:  The member will be serialized as an XML element.
  • SoapEnum:  The element name of an enumeration member.
  • SoapIgnore:  The member will not be serialized.
  • SoapInclude:  The type should be included when generating schemas.

No comments:

Post a Comment

Bookmark and Share