This section deals with some of the points that we have
already covered in this article and some others that we have not, but are still
very important and relate to the serialization and de-serialization concepts of
.NET.
When you apply the Serializable custom attribute to a type,
all instance fields of the class (public, private, protected, etc.) are
serialized automatically.
XmlSerializer does not use the ISerializable interface;
rather, it uses the IXmlSerializable interface. The XmlSerializer class can
only serialize the public properties of the class, whereas the BinaryFormatter
class can serialize private fields using the ISerializable interface.
The Serializable attribute is a must for making a class
serializable irrespective of whether we have implemented the ISerializable
interface in this class. When we serialize a class, the objects of the
references to other classes that are contained in this class are also
serialized if they are marked as serializable. All members are serialized,
including public, private or protected members. Furthermore, even circular
references are supported by binary serialization. Note that read only properties
are not serialized except the collection class objects. However, the read only
properties can be serialized using binary serialization.
If we do not require serializing a particular property of a
class when using an XmlSerializer, we have to mark the property with the custom
attribute XmlIgnoreAttribute. When using a SoapFormatter we have to use the
SoapIgnoreAttribute instead. The XmlSerializer generates an in-memory assembly
optimized for each type since the initial invocation to a Web Service always
takes so much time. To combat this, we can use the sgen.exe tool to pre-generate
the serialization assembly.